r - 如何使用 R 遍历子文件夹并绑定(bind)相同 ID 的 CSV 文件?

标签 r

我被困住了。我需要一种方法来遍历目录中的一堆子文件夹,提取 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 的菜鸟。可能涉及函数 pastewrite.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/

相关文章:

r - Stargazer 中的 p 值不精确

r - R包中的src-{i386,x64}文件夹

R问题。绘制响应时出现无法解释的空因子组合

RStudio - 更改默认代码块

mysql - 使用 R 将字符向量转换为字符串(带引号和逗号)

r - 在 Azure 中创建运行 R 脚本的管道,而无需通用化 VM

r - 在 R 中,将两个数据帧按元素相乘并乘以一个向量

r - 在 R 中的两个数据框中使用多行过滤

r - 如何对r中的几列求和?

r - 如何 : Automatically set fixed coordinate ratio (coord_fixed) when x- and y-axis are on different scales?