让我们首先选择我们的Sample_*
目录。
main_dir <- '/home/Project1/Files/'
directories <- list.files(main_dir, pattern = '^Sample_')
directories <- Filter(function(x) file.info(file.path(main_dir, x))$isdir, directories)
我们现在有一个以 开头的目录的字符向量Sample_
。现在我们可以读入我们的data.frames:
dfs <- lapply(directories, function(subdir) {
files <- list.files(path <- file.path(main_dir, subdir), pattern = '\\.QC\\.dat$')
subdfs <- lapply(files, function(filename)
read.table(file.path(path, filename), header=TRUE, sep="\t", stringsAsFactors=FALSE)
)
do.call(rbind, subdfs)
})
最后,我们将它们绑定到一个巨大的数据框中:
dfs <- do.call(rbind, dfs) # Notice we used the same trick twice
一个更短但更聪明的选择是使用recursive = TRUE
参数 on list.files
:
dfs <- do.call(rbind, lapply(
list.files(path <- '/home/Project1/Files/',
pattern = '^Sample_.*\\.QC\\.dat$', recursive = TRUE),
function(filename)
read.table(file.path(path, filename), header=TRUE, sep="\t", stringsAsFactors=FALSE)
))