loading and naming multiple files into R

偶尔善良 提交于 2019-12-12 18:33:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!