R for 遍历目录和所有子目录中的所有文件

R for loop over all files in directory and in all subdirectories

我不确定如何使用多个目录创建可重现的数据,所以我将解释我的目录结构。

我有一个名为 Data 的父文件夹。在Data下,我有几十个名为Sample1Sample2Sample3等的文件夹。每个文件夹都有 txt 个格式相同的文件。

我目前有一个循环可以处理 Sample1 中的所有文件,如下所示:

file_list <- list.files(path = "C:/Users/username/Desktop/Data/Sample1/", pattern = "*.txt", full.names = T)
all_list <- vector("list", "length" = length(file_list)

for (i in seq_along(file_list)){
   filename <- file_list[[i]]

   ## I do more things here, but I'm abbreviating this part to make the question simpler
   df1 <- read.table(filename, sep = " ")
   df1$col1 <- df1$col2 + df1$col3

   all_list[[i]] <- df1
}

all_df <- do.call(rbind, all_list)

现在我试图让这段代码适用于 Data 下的所有文件夹(Sample1Sample2、....)。我使用以下代码提取了文件夹路径:

parent_folder <- "C:/Users/username/Desktop/Data"
sub_folders <- list.dirs(parent_folder, recursive = TRUE) [-1]

我需要对所有这些 sub_folders 重复上面的循环。我认为循环的开始看起来像这样:

for (j in seq_along(sub_folders)){
   all_file_list <- vector("list", length = length(sub_folders)
   file_list <- list.files(path = sub_folders[j], pattern = "*.txt", full.names = T)
   ...
}

然后我现在开始有点迷糊了,因为列表好像太多了。上面代码中的 file_listall_listall_df(在 Sample1 文件夹中工作)都需要保存为列表,以便它可以包含来自所有sub_folders?这也感觉效率不高,但我不确定是否有办法让这更简单。谁能给我一些尝试的建议?

也许您可以使用 dir_ls() function from the fs package 递归查找所有需要的文件,即

library(fs)
file_list <- fs::dir_ls(path = "C:/Users/username/Desktop/Data/Sample1/", recurse = TRUE, type = "file", glob = "*.txt")

然后将该文件列表 paths/names 传递给 vroom 以将它们读入单个数据帧,对那个大数据帧进行数据操作 'once',然后将大数据帧拆分为较小的数据帧(每个样本一个):

library(vroom)
data <- vroom::vroom(file_list, id = "sample")
data$col1 <- data$col2 + data$col3

# split the df into smaller dfs (one df per sample)
list_of_dfs <- split(data, data$sample)
list2env(list_of_dfs, envir = .GlobalEnv)

我不知道这是否适用于您的预期目的(也许 'large' 数据框对于您的系统来说太大而无法处理),但我在我的一个项目中使用了类似的工作流程并且它比使用 for 循环读取和操作每个 'sample' 快得多。