我正在尝试读取一个文件列表,并将它们附加到一个包含所有记录的新文件中。我不打算更改原始文件中的任何内容。我已经尝试了几种方法。
**方法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)
}
有人能给我一些建议,告诉我如何实现目标吗?
6条答案
按热度按时间gz5pxeao1#
它可能如下所示:
或更短:
k2fxgqgv2#
您可以使用它将所有内容加载到一个数据集中。
然后保存为
write.csv
。lrl1mhuk3#
或者,您可以在R:
这适用于基于UNIX的系统;我不知道你会为Windows做什么。
2vuwiymt4#
对于文件名列表,请尝试以下操作:
来源:https://r.789695.n4.nabble.com/R-Read-multiple-text-files-and-combine-into-single-file-td817344.html
eivnm1vs5#
rbind_list()
现在有一个简单的答案!例如:
或者将文件读入列表的方式
和
dat
将是你要找的!wa7juj8i6#
如果使用的是Windows,使用命令提示符很容易做到这一点。
开始-〉运行-〉键入“cmd”并按回车键
具体例子:
请注意,如果要在cd之前更改驱动器号