问题描述
假设我们有一个包含多个data.csv文件的文件夹,每个文件包含相同数量的变量,但每个变量来自不同的时间。
要同时导入它们而不是单独导入它们?
我的问题是,我有大约2000个数据文件要导入,必须通过使用代码:
read.delim(file =filename,header = TRUE,sep =\t)
效率不高。
类似以下内容应该工作:
temp = list.files(pattern =*。 csv)
myfiles = lapply(temp,read.delim)
将这些CSV存储在单个目录(您当前的工作目录)中,并且所有这些CSV都具有小写扩展名 .csv
。
更新
快速和脏的解决方案,以获得单独的data.frames(脏,因为我没有打扰清除 .csv
扩展,但这很容易与一些 regex
有关:
temp = list.files(pattern =*。csv)
for(i in 1:length(temp))assign(temp [i],read。 csv(temp [i]))
或者, c $ c>,并演示(1)如何清除文件名和(2)显示如何使用
list2env
,您可以尝试以下: p>
temp = list.files(pattern =*。csv)
pre>
list2env(
lapply temp,make.names(gsub(*。csv $,,temp))),
read.csv),envir = .GlobalEnv)
Suppose we have a folder containing multiple data.csv files, each containing the same number of variables but each from from different times.
Is there a way in R to import them all simultaneously rather than having to import them all individually?
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="\t")
is not very efficient.
解决方案Something like the following should work:
temp = list.files(pattern="*.csv") myfiles = lapply(temp, read.delim)
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
.Update
Quick and dirty solution to get separate data.frames ("dirty" because I haven't bothered to clean up the
.csv
extension, but that's easy enough to do with someregex
):temp = list.files(pattern="*.csv") for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))
Or, without
assign
, and to demonstrate (1) how the file name can be cleaned up and (2) show how to uselist2env
, you can try the following:temp = list.files(pattern="*.csv") list2env( lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))), read.csv), envir = .GlobalEnv)
这篇关于将多个.csv文件导入到R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!