2013-03-02 49 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=",") 
相關問題