【问题标题】:list files recursive up to a certain level in R列表文件递归到R中的某个级别
【发布时间】:2018-01-17 09:17:06
【问题描述】:

有没有一种优雅的方式来列出递归到某个级别的文件? 我有一个非常复杂的文件夹结构,递归搜索所有xml 文件需要几秒钟。对我来说,只搜索到某个级别就足够了,但是我开发的代码看起来很难看,我想知道是否有更优雅的方法。例如,搜索到第 4 级会变得很丑......

list.files(c(list.dirs(recursive=FALSE), # first level
             list.dirs(list.dirs(recursive=FALSE), recursive=FALSE)), # second level 
             pattern='\\.xml$',
             full.names=TRUE, 
             recursive=FALSE)

【问题讨论】:

  • 也许将 recursive 设置为 TRUE 并使用过滤器丢弃超过 N 个 "/" 的实例?
  • list.dirs 函数已经花费了很长时间,因为复杂的文件夹结构......所以我宁愿只搜索到特定深度。

标签: r


【解决方案1】:

为了优雅,我会编写一个带有n 参数的小型递归实用程序,您可以在之后使用它。例如。类似:

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)

然后在你对list.files的调用中使用它

【讨论】:

  • 这是我尝试过的,但我无法让它以某种方式运行......会试一试。
【解决方案2】:

这是使用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)

【讨论】:

    【解决方案3】:

    此示例与递归解决方案 #1 非常相似,但它是针对文件完成的。

    lfbl=function(pattern,level=1){
        if(!exists("lof")) lof=vector("character",0)
        temp=list.files(pattern=pattern,no..=T)
        if(!is.na(temp[1])) lof=c(lof,paste0(getwd(),"/",temp))
        if(level>0){
            dirf=list.dirs(full.names=F,recursive=F)
            for(i in dirf){
                setwd(i)
                lof=c(lof,lfbl(pattern,level-1))
                setwd("..")
            }
        }
        return(lof)
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-15
      • 1970-01-01
      • 2021-10-20
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 2015-08-04
      相关资源
      最近更新 更多