【问题标题】:How to rbind multiple files with a loop? [duplicate]如何使用循环 rbind 多个文件? [复制]
【发布时间】:2014-08-29 17:38:09
【问题描述】:

我有一组 30 个具有通用根名称的文件(例如 file-0001、file-0002 等),它们具有相同的变量名称(同一目录中的所有文件),我想附加到主数据集。我该怎么做?

【问题讨论】:

    标签: r for-loop rbind


    【解决方案1】:

    你可以试试(如果所有文件都在同一个工作目录下)

     files <- list.files(pattern="file-[0-9]+")
    
     res1 <- do.call(`rbind`,lapply(files, read.table, header=T))
    

    或者

     library(data.table) 
     rbindlist(lapply(files, fread))
    

    【讨论】:

      【解决方案2】:

      使用list.files 按照特定模式获取特定文件夹中的所有文件,例如:

      DF <- masterDF
      filePaths <- list.files(path="folderpath",pattern="file-[0-9]+",include.dirs=T)
      for(filePath in filePaths){
        currentDF <- read.table(filePath)
        DF <- rbind(DF, currentDF)
      }
      

      【讨论】:

        【解决方案3】:

        用所有文件的名称和一个 id 制作一个表格,然后编写如下内容:

        #load the table with the name of the file & id
        list<-read.table("Table.txt",header=T)
        
        #define the range
        i=max(list$id)+1
        
        #make the loop
        while (i>0)
        i=i-1
        
        #select the name of your file from the table
        for(i in 1:length(list[,1])) {if (list[i,1]==id) {file<-list[i,2]} }
        file
        
        #set work directory
        setwd(your directory)
        
        #use your function
        result<-rbind(file)
        

        将算法更改为您自己的工作!

        【讨论】:

          猜你喜欢
          • 2018-05-29
          • 2020-09-11
          • 1970-01-01
          • 2018-05-10
          • 2012-10-12
          • 2017-08-23
          • 2015-04-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多