如何一次导入多个 .csv 文件? [英] How to import multiple .csv files at once?
问题描述
假设我们有一个文件夹,其中包含多个 data.csv 文件,每个文件包含相同数量的变量,但每个都来自不同的时间.R 中有没有办法同时导入它们,而不必单独导入它们?
Suppose we have a folder containing multiple data.csv files, each containing the same number of variables but each from different times. Is there a way in R to import them all simultaneously rather than having to import them all individually?
我的问题是我有大约 2000 个数据文件要导入,并且必须使用代码单独导入它们:
My problem is that I have around 2000 data files to import and having to import them individually just by using the code:
read.delim(file="filename", header=TRUE, sep=" ")
效率不高.
推荐答案
类似于下面的内容应该导致每个数据框作为单个列表中的单独元素:
Something like the following should result in each data frame as a separate element in a single list:
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)
这假设您在单个目录(您当前的工作目录)中拥有这些 CSV,并且所有这些文件的扩展名都是小写的 .csv
.
This assumes that you have those CSVs in a single directory--your current working directory--and that all of them have the lower-case extension .csv
.
如果您随后想将这些数据帧合并为一个数据帧,请使用 do.call(rbind,...)
、dplyr 之类的内容查看其他答案中的解决方案::bind_rows()
或 data.table::rbindlist()
.
If you then want to combine those data frames into a single data frame, see the solutions in other answers using things like do.call(rbind,...)
, dplyr::bind_rows()
or data.table::rbindlist()
.
如果您确实希望将每个数据框放在一个单独的对象中,即使这通常是不可取的,您也可以使用 assign
执行以下操作:
If you really want each data frame in a separate object, even though that's often inadvisable, you could do the following with assign
:
temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))
或者,不使用 assign
,并演示 (1) 如何清理文件名和 (2) 演示如何使用 list2env
,您可以尝试以下:
Or, without assign
, and to demonstrate (1) how the file name can be cleaned up and (2) show how to use list2env
, you can try the following:
temp = list.files(pattern="*.csv")
list2env(
lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))),
read.csv), envir = .GlobalEnv)
但同样,将它们放在一个列表中通常会更好.
But again, it's often better to leave them in a single list.
这篇关于如何一次导入多个 .csv 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!