Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中附加多个文件_R_File_Csv_Append - Fatal编程技术网

如何在R中附加多个文件

如何在R中附加多个文件,r,file,csv,append,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 =

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

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

有人能就如何实现我的目标向我提供建议吗?

您可以使用此功能将所有内容加载到一个数据集中

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

dataset它可能如下所示:

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)

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

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

这将适用于基于unix的系统;我不确定您将为windows做什么。

请在您的电子邮件列表中尝试以下内容:

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)

ListOfFileNames现在就有一个简单的答案,就是
rbind\u list()

例如:

dataFiles = map(Sys.glob("*.csv"), read.csv) 
或者以何种方式将文件读入列表

dat = rbind_list(dataFiles)
dat
将是您所寻找的

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