【发布时间】:2016-02-07 12:08:43
【问题描述】:
我正在尝试读取文件列表并将它们附加到包含所有记录的新文件中。我不打算更改原始文件中的任何内容。我已经尝试了几种方法。
方法 1: 此方法会创建一个新文件,但在每次迭代时都会再次添加前一个文件。因为我是递归绑定数据框的。
files <- list.files(pattern = "\\.csv$")
#temparary data frame to load the contents on the current file
temp_df <- data.frame(ModelName = character(), Object = character(),stringsAsFactors = F)
#reading each file within the range and append them to create one file
for (i in 1:length(files)){
#read the file
currentFile = read.csv(files[i])
#Append the current file
temp_df = rbind(temp_df, currentFile)
}
#writing the appended file
write.csv(temp_df,"Models_appended.csv",row.names = F,quote = F)
方法2:我从Rbloggers得到这个方法。此方法不会写入新文件,但会继续修改原始文件。
multmerge = function(){
filenames= list.files(pattern = "\\.csv$")
datalist = lapply(filenames, function(x){read.csv(file=x,header=T)})
Reduce(function(x,y) {merge(x,y)}, temp_df)
}
有人可以建议我如何实现我的目标吗?
【问题讨论】: