2015-11-06 39 views
2

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

} 

有人能告訴我如何實現我的目標嗎?

回答

3

它可能看起來像這樣:

files <- list.files(pattern = "\\.csv$") 

DF <- read.csv(files[1]) 

#reading each file within the range and append them to create one file 
for (f in files[-1]){ 
    df <- read.csv(f)  # read the file 
    DF <- rbind(DF, df) # append the current file 
} 
#writing the appended file 
write.csv(DF, "Models_appended.csv", row.names=FALSE, quote=FALSE) 

或短:

files <- list.files(pattern = "\\.csv$") 

DF <- read.csv(files[1]) 
for (f in files[-1]) DF <- rbind(DF, read.csv(f)) 
write.csv(DF, "Models_appended.csv", row.names=FALSE, quote=FALSE) 
5

您可以使用它將所有內容加載到一個數據集中。

dataset <- do.call("rbind", lapply(file.list, FUN = function(file) { 
    read.table(file, header=TRUE, sep="\t") 
})) 

然後只是write.csv保存。