如何使用R迭代子文件夹并绑定相同ID的CSV文件?

时间:2013-03-02 01:02:09

标签: r

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

我知道 R可以做到这一点。但我坚持如何遍历子文件夹并将csv文件绑定在一起。我的障碍是每个子文件夹包含相同的4个.csv文件,使用相同的8位数ID。例如,子文件夹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也许?非常感谢任何提示/帮助/建议。谢谢!

2 个答案:

答案 0 :(得分:13)

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

 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='')
   }

答案 1 :(得分: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=",")
相关问题