How to obtain a list of directories within a directory, like list.files(), but instead “list.dirs()”

后端 未结 7 615
梦如初夏
梦如初夏 2021-01-30 12:14

This may be a very easy question for someone - I am able to use list.files() to obtain a list of files in a given directory, but if I want to get a list of director

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 12:56

    I had this problem a while back and used this recursive code to find all directories. Perhaps this can be of use?

    list.dirs <- function(parent=".")   # recursively find directories
    {
        if (length(parent)>1)           # work on first and then rest
            return(c(list.dirs(parent[1]), list.dirs(parent[-1])))
        else {                          # length(parent) == 1
            if (!is.dir(parent))
                return(NULL)            # not a directory, don't return anything
            child <- list.files(parent, full=TRUE)
            if (!any(is.dir(child)))
                return(parent)          # no directories below, return parent
            else 
                return(list.dirs(child))    # recurse
        }
    }
    
    is.dir <- function(x)    # helper function
    {
        ret <- file.info(x)$isdir
        ret[is.na(ret)] <- FALSE
        ret
    }
    

提交回复
热议问题