我对R很新,我需要一些帮助。我有多个标记为001到332的csv文件。我想将它们全部合并到一个data.frame中。这是我到目前为止所做的:
filesCSV <- function(id = 1:332){
fileNames <- paste(id) ## I want fileNames to be a vector with the names of all the csv files that I want to join together
for(i in id){
if(i < 10){
fileNames[i] <- paste("00",fileNames[i],".csv",sep = "")
}
if(i < 100 && i > 9){
fileNames[i] <- paste("0", fileNames[i],".csv", sep = "")
}
else if (i > 99){
fileNames[i] <- paste(fileNames[i], ".csv", sep = "")
}
}
theData <- read.csv(fileNames[1], header = TRUE) ## here I was trying to create the data.frame with the first csv file
for(a in 2:332){
theData <- rbind(theData,read.csv(fileNames[a])) ## here I wanted to use a for loop to cycle through the names of files in the fileNames vector, and open them all and add them to the 'theData' data.frame
}
theData
}
任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
嗯,看起来你的功能应该已经开始了。有什么问题? 无论如何,这将是一个更惯用的R方式来实现你想要做的事情,将整个功能减少到三行代码:
构建文件名:
infiles <- sprintf("%03d.csv", 1:300)
%03d
表示:插入一个填充长度为d
零(3
)的整数值0
。有关详细信息,请参阅?sprintf()
的帮助。
阅读文件:
res <- lapply(infiles, read.csv, header = TRUE)
lapply将函数read.csv
与参数header = TRUE
映射到向量的每个元素&#34; infiles&#34;并返回list
(在这种情况下为list
的{{1}})
将数据框绑定在一起:
data.frames
这与输入do.call(rbind, res)
相同,其中rbind(df1, df2, df3, df4, ..., dfn)
是df1...dfn
list
答案 1 :(得分:0)
你很亲密;只需要将3-10
附加到文件中的想法,以及在最终数据应该只读取csv或是0
rbind