gpt4 book ai didi

r - 如何在R中 append 多个文件

转载 作者:行者123 更新时间:2023-12-04 10:46:42 26 4
gpt4 key购买 nike

我正在尝试 读取文件列表并将它们 append 到包含所有记录的新文件中 .我不打算更改原始文件中的任何内容。我尝试了几种方法。

方法一:此方法会创建一个新文件,但在每次迭代时,都会再次添加前一个文件。因为我正在递归地绑定(bind)数据框。

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)

方法二:我从 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)

}

有人可以建议我如何实现我的目标吗?

最佳答案

或者你可以继续在 R 中使用 shell 命令:

system2("cat", args = "*.csv", stdout = "appendedfiles.csv")

这适用于基于 Unix 的系统;我不确定你会为 Windows 做什么。

关于r - 如何在R中 append 多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33565199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com