【问题标题】:Merge multiple .txt files from multiple directories in R合并来自 R 中多个目录的多个 .txt 文件
【发布时间】:2014-08-06 18:08:59
【问题描述】:

合并不同子目录的.txt文件

我有一个文件夹,里面装满了过去日期的子文件夹(例如 01_14),每个日期文件夹内有 11 个名为 01.txt、02.txt 的文件...如何合并所有的 .txt 文件到一个数据框中,一列是它来自的文件夹的名称,一列是它来自的文件名?

我的层次结构看起来像这样:

\Data
     \01_14
           01.txt
           02.txt
           ...
           11.txt 
     \02_14
           01.txt
           02.txt
           ...
           11.txt 
     \03_14
           01.txt
           02.txt
           ...
           11.txt 

【问题讨论】:

    标签: r merge dataframe rstudio dir


    【解决方案1】:

    当我需要读取多个文件时,我使用 read.stack 辅助函数,它基本上是 read.table 的包装器,但它还允许您在每个文件的基础上添加额外的列。以下是我可能会在您的场景中使用它的方法。

    dir<-"Data"
    
    subdir<-list.dirs(dir, recursive=F)
    
    #get dir/file names
    ff<-do.call(rbind, lapply(subdir, function(x) {
        ff<-list.files(x, "\\.txt$", include.dirs = FALSE, full.names = TRUE)
        data.frame(dir=basename(x), file=basename(ff), 
            fullpath=ff, stringsAsFactors=F)
    }))
    
    #read into data.frame
    read.stack(ff$fullpath, extra=list(file=ff$file, dir=ff$dir))
    

    【讨论】:

      【解决方案2】:

      试试这个:

      fileNames <- list.files("Data", recursive = TRUE, full.names = TRUE)
      fileContents <- lapply(fileNames, function(fileName) 
        paste(readLines(fileName, warn = FALSE), collapse = "\n"))
      meta <- regmatches(fileNames, regexec(".*Data/(.*)/(.*)$", fileNames))
      merged <- mapply(c, fileContents, lapply(meta, "[", -1), SIMPLIFY = FALSE)
      as.data.frame(t(do.call(cbind, merged)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-02
        • 1970-01-01
        • 2021-06-04
        • 2020-07-09
        相关资源
        最近更新 更多