如何在R中附加多个文件

时间:2015-11-06 10:55:03

标签: r file csv append

我尝试读取文件列表并将其附加到包含所有记录的新文件。我不打算改变原始文件中的任何内容。我尝试了几种方法。

方法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)

}

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

5 个答案:

答案 0 :(得分:6)

您可以使用它将所有内容加载到一个数据集中。

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

然后只需保存write.csv

答案 1 :(得分:5)

它看起来像这样:

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)

答案 2 :(得分:1)

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

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

这将用于基于Unix的系统;我不确定您将如何使用Windows。

答案 3 :(得分:1)

为您的ListOfFileNames尝试以下操作:

ListOfFileNames<-list.files(pattern=".txt")
outFile <- file("all.txt", "w")
for (i in ListOfFileNames){
    x <- readLines(i)
    writeLines(x, outFile) # in the link the 1st and last line are skipped
}
close(outFile)

来源:https://r.789695.n4.nabble.com/R-Read-multiple-text-files-and-combine-into-single-file-td817344.html

答案 4 :(得分:0)

rbind_list()现在有一个简单的答案!

例如:

dataFiles = map(Sys.glob("*.csv"), read.csv) 

或者您正在将文件读入列表

dat = rbind_list(dataFiles)

dat将是您想要的!