Is there an elegant way to list files recursive up to a certain level?
I have a very complicated folder structure und it takes several seconds to search for all xml
Here is a way using Sys.glob
:
getFiles <- function(ext, depth){
wildcards <- Reduce(
file.path, x = rep("*", depth), init = paste0("*.", ext),
right = TRUE, accumulate = TRUE
)
Sys.glob(wildcards)
}
getFiles("xml", 4)
For elegance, I would write a small recursive utility with an n
parameter that you can use afterwards. E.g. something like:
list.dirs.depth.n <- function(p, n) {
res <- list.dirs(p, recursive = FALSE)
if (n > 1) {
add <- list.dirs.depth.n(res, n-1)
c(res, add)
} else {
res
}
}
list.dirs.depth.n(".", n = 3)
And then use this in your call to list.files