问题
I have over 1000 data sets I would like to load into R and name each one separately as they are loaded in. I found that to load them I can use the commands:
temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))
but how would I name each file as it is loaded so I can easily call each one later on?
回答1:
It is better to get your data.frame aggregated in a list.
Using sapply to loop you get a named list with file names.
temp = list.files(pattern="*.csv")
named.list <- sapply(temp, read.csv)
EDIT
To avoid the case of data frames with the same number of columns, you need to set simplify=FALSE
named.list <- sapply(temp, read.csv,simplify=FALSE)
回答2:
You simply need a list of data.frame names, similar to your list of file names.
Then everything else is almost the same, except for a small change in your assign statement
temp = list.files(pattern="*.csv")
# just an example
dataNames <- paste0(c("dataSource_", 1:length(temp)))
# then everything else is almost the same
for (i in 1:length(temp))
assign(dataNames[i], read.csv(temp[i]))
来源:https://stackoverflow.com/questions/15056672/loading-and-naming-multiple-files-into-r