我正在嘗試讀取文件列表並將它們追加到一個新文件中,其中包含所有記錄。我不打算改變原始文件中的任何內容。我試過幾種方法。如何在R中追加多個文件
方法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)
}
有人能告訴我如何實現我的目標嗎?