Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I have these files:

N1.xlsx
N2.xlsx
N3.xlsx
N4.xlsx

I want them in a list, but each dataframe must be named according to the file it was read from, like

mylist = 
N1
N2
N3
N4

I'm using:

fnames =  mixedsort(sort(list.files("filepath", pattern = '*.xlsx', full.names = F)))

mylist <- lapply(fnames, function(x) {
 read_xlsx(paste0(x),  col_names = TRUE)
})

But this code creates a list without identification

mylist = 
[[1]]
[[2]]
[[3]]
[[4]]

Its important to keep the names of each file in each dataframe, so I can export them correctly later!

question from:https://stackoverflow.com/questions/65865409/read-multiple-files-but-keep-track-of-which-file-is-which-dataframe-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
828 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could name mylist with the names you already have in fnames.

names(mylist) <- tools::file_path_sans_ext(fnames)
mylist

file_path_sans_ext remove extension from the filenames.

If you want to rename anything in the file name (for example N1 any text.xlsx), you could use

names(mylist) <- tools::file_path_sans_ext(str_remove(fnames, " any  text"))
mylist

Or even:

names(mylist) <- tools::file_path_sans_ext(str_replace(fnames, " any  text", "other text"))
mylist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...