list files recursive up to a certain level in R

前端 未结 2 1548
闹比i
闹比i 2021-01-21 10:01

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

相关标签:
2条回答
  • 2021-01-21 10:38

    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)
    
    0 讨论(0)
  • 2021-01-21 10:41

    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

    0 讨论(0)
提交回复
热议问题