2013-03-02 22 views
7

我被卡住了。我需要一种方法来遍历目录中的一堆子文件夹,提取4个.csv文件,绑定这些4个.csv文件的内容,然后使用初始子文件夹的名称将新的.csv写入新目录作为新的.csv的名称。如何使用R来遍历子文件夹并绑定具有相同ID的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也许是一个小白?任何提示/帮助/建议非常感谢。谢谢!

回答

12

您可以使用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='') 
    } 
+0

非常感谢@agstudy! – myClone 2013-03-04 17:37:56

1

的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=",") 
相关问题