csv 如何在R中追加多个文件

yiytaume  于 2022-12-06  发布在  其他
关注(0)|答案(6)|浏览(147)

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

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

}

有人能给我一些建议,告诉我如何实现目标吗?

gz5pxeao

gz5pxeao1#

它可能如下所示:

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)
k2fxgqgv

k2fxgqgv2#

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

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

然后保存为write.csv

lrl1mhuk

lrl1mhuk3#

或者,您可以在R:

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

这适用于基于UNIX的系统;我不知道你会为Windows做什么。

2vuwiymt

2vuwiymt4#

对于文件名列表,请尝试以下操作:

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

eivnm1vs

eivnm1vs5#

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

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

或者将文件读入列表的方式

dat = rbind_list(dataFiles)

dat将是你要找的!

wa7juj8i

wa7juj8i6#

如果使用的是Windows,使用命令提示符很容易做到这一点。
开始-〉运行-〉键入“cmd”并按回车键

cd <path to folder>
copy /b *.txt <outputname>.txt

具体例子:

cd C:\User\danny\docs\folder_with_txt files
copy /b *.txt concatenated.txt

请注意,如果要在cd之前更改驱动器号

D:\> c:
C:\> cd C:\User\danny\docs\folder_with_txt files
copy /b *.txt concatenated.txt

相关问题