【问题标题】:How to use R to Iterate through Subfolders and bind CSV files of the same ID?如何使用 R 遍历子文件夹并绑定相同 ID 的 CSV 文件?
【发布时间】:2013-03-02 01:02:08
【问题描述】:

我被困住了。我需要一种方法来遍历目录中的一堆子文件夹,提取 4 个 .csv 文件,绑定这 4 个 .csv 文件的内容,然后使用初始子文件夹的名称将新的 .csv 写入新目录作为新 .csv 的名称。

我知道 R 可以做到这一点。但我被困在如何遍历子文件夹并将 csv 文件绑定在一起。我的障碍是每个子文件夹都包含使用相同的 8 位 id 的相同 4 个 .csv 文件。例如,子文件夹 A 包含 09061234.csv、09061345.csv、09061456.csv 和 09061560.csv。子文件夹 B 包含 9061234.csv、09061345.csv、09061456.csv 和 09061560.csv。 (...)。有 42 个子文件夹,因此有 168 个同名的 csv 文件。我想将文件压缩到 42 个。

我可以使用list.files 检索所有子文件夹。但是然后呢?

##Get Files from directory
TF = "H:/working/TC/TMS/Counts/June09" 
##List Sub folders
SF <- list.files(TF)
##List of File names inside folders
FN <- list.files(SF)
#Returns list of 168 filenames

###?????###
#How to iterate through each subfolder, read each 8-digit integer id file, 
#bind them all together into one single csv, 
#Then write to new directory using 
#the name of the subfolder as the name of the new csv?

可能有一种方法可以轻松做到这一点,但我是 R 的菜鸟。可能涉及到函数的东西,pastewrite.table?非常感谢任何提示/帮助/建议。谢谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以为list.files 使用recursive=T 选项,

     lapply(c('1234' ,'1345','1456','1560'),function(x){
         sources.files  <- list.files(path=TF,
                                    recursive=T,
                                    pattern=paste('*09061*',x,'*.csv',sep='')
                                    ,full.names=T)
          ## ou read all files with the id and bind them
          dat <- do.call(rbind,lapply(sources.files,read.csv))
          ### write the file for the 
          write(dat,paste('agg',x,'.csv',sep='')
       }
    

    【讨论】:

    • 如此简单!不错!
    【解决方案2】:

    在对 agstudy 的代码进行了一些调整后,我想出了我最终想要的解决方案。由于我的具体问题的性质,有一些缺失的部分更多,所以我将 agstudy 的答案保留为“已接受”。

    原来真的不需要一个函数。至少现在不会。如果我需要再次执行相同的任务,我将创建一个函数。目前,我可以在没有它的情况下解决这个特殊问题。

    另外,就我而言,我需要一个条件“if”语句来处理可能存在于子文件夹中的任何非 csv 文件。通过添加 if 语句,R 会抛出警告并跳过任何非逗号分隔的文件。
    代码:

    ##Define directory path##
    TF = "H:/working/TC/TMS/Counts/June09" 
    ##List of subfolder files where file name starts with "0906"##
    SF <- list.files(TF,recursive=T, pattern=paste("*09061*",x,'*.csv',sep=""))
    ##Define the list of files to search for##
    x <- (c('1234' ,'1345','1456','1560')
    ##Create a conditional to skip over the non-csv files in each folder##
    if (is.integer(x)){
      sources.files  <- list.files(TF, recursive=T,full.names=T)}
    
    dat <- do.call(rbind,lapply(sources.files,read.csv))
    #the warnings thrown are ok--these are generated due to the fact that some of the folders contain .xls files
    write.table(dat,file="H:/working/TC/TMS/June09Output/June09Batched.csv",row.names=FALSE,sep=",")
    

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 2018-01-16
      • 1970-01-01
      • 2021-12-31
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多