我被困住了。我需要一种方法来遍历目录中的一堆子文件夹,提取 4 个 .csv 文件,绑定(bind)这 4 个 .csv 文件的内容,然后使用初始子文件夹的名称将新的 .csv 写入新目录作为新 .csv 的名称。
我知道 R 可以做到这一点。但我被困在如何遍历子文件夹并将 csv 文件绑定(bind)在一起。我的障碍是每个子文件夹都包含使用相同的 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 的菜鸟。可能涉及函数
paste
和 write.table
的东西?非常感谢任何提示/帮助/建议。谢谢!
最佳答案
您可以为 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='')
}
关于r - 如何使用 R 遍历子文件夹并绑定(bind)相同 ID 的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15169446/