Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 views
in Technique[技术] by (71.8m points)

lapply - Read multiple files but keep track of which file is which dataframe in R

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...