How to merge csv files from nested folders in R

前端 未结 3 1295
陌清茗
陌清茗 2020-12-21 10:52

I have a large collection of csv files that are in different folders and in folders within folders that I need to merge into one file. It would be easy if they were all in o

3条回答
  •  -上瘾入骨i
    2020-12-21 11:34

    This solution has the assumption that all *.csv files have the same structure.

    (Untested)

    fileList <- list.files(
      pattern="*.csv$",
      recursive=TRUE,
      full.name=TRUE,
      )
    
    completeCSV <- data.frame()
    
    
    for(file in fileList) {
      print(file) # for debug: print current file
      if (nrow(completeCSV) == 0) {
        completeCSV <- read.csv(file)
      } else {
        curDF <- read.csv(file) # could also be read.csv2()
        rbind(completeCSV, curDF)
      }
    }
    
    write.csv(completeCSV) # could also be write.csv2()
    

提交回复
热议问题