读取for循环中的csv文件并分配数据帧名称 [英] reading csv files in a for loop and assigning dataframe names

查看:138
本文介绍了读取for循环中的csv文件并分配数据帧名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我需要从一个文件夹中将许多csv文件读入数据框。 csv文件名称格式为 fxpair-yyyy-mm.csv (例如AUDJPY-2009-05.csv)。我想读取所有csv文件并创建 fxpair.yyyy.mm

I need to read many csv files into dataframes from one folder. The csv file names are of the form fxpair-yyyy-mm.csv (e.g. AUDJPY-2009-05.csv). I want to read all csv files in and create dataframes of the form fxpair.yyyy.mm

我是无法在循环中为read.csv语句创建数据框名称

I am having trouble creating the dataframe names in the loop for assignment from the read.csv statements

filenames <- list.files(path=getwd())  
numfiles <- length(filenames)  

#fx.data.frames to hold names that will be assigned to csv files in csv.read
fx.data.frames <- gsub(pattern="-",x=filenames,replacement=".")  
fx.data.frames <- gsub(pattern=".csv",x=fx.data.frames,replacement="")

i <-1  
for (i in c(1:numfiles)){  
   filenames[i] <- paste(".\\",filenames[i],sep="")  
   fx.data.frames[i] <- read.csv(filenames[i], header=FALSE)
}

csv.read似乎工作正常,但是我无法创建数据帧对象我打算的方式。我只是想要一些方法来命名基于文件名的 fxpair.yyyy.mm 格式的数据框。

The csv.read seems to work fine but I am not able to create the dataframe objects in the way I intend. I just want some way to name the dataframes read in the fxpair.yyyy.mm format based on the file name.

推荐答案

Just to illustrate my comment : 

或者,将所有数据框保存在列表中:

for (i in filenames){ name <- gsub("-",".",i) name <- gsub(".csv","",name) i <- paste(".\\",i,sep="") assign(name,read.csv(i, header=FALSE) }

Or, to save all dataframes in a list :



'I'第二个解决方案,因为我喜欢清单工作,清理工作空间不麻烦,也可以去掉名称和<$ c在全球环境中,这些可能会导致一些有趣的错误,如果你不小心的话。 R还是应用家庭而不是语法糖?

All <- lapply(filenames,function(i){ i <- paste(".\\",i,sep="") read.csv(i, header=FALSE) }) filenames <- gsub("-",".",filenames) names(All) <- gsub(".csv","",filenames)

这篇关于读取for循环中的csv文件并分配数据帧名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆