开发者

How does one use `Recall()` to write a recursive function to recursively list directories in a given directory?

开发者 https://www.devze.com 2023-02-06 00:49 出处:网络
This Question asked about listing directories (not files) in the current directory. I noted in a comment to one of the an开发者_开发百科swers that we can\'t use the recursive argument of functions lik

This Question asked about listing directories (not files) in the current directory. I noted in a comment to one of the an开发者_开发百科swers that we can't use the recursive argument of functions like dir and list.files to recursively list directories in the current directory.

The obvious solution to this is to write a recursive function that lists the directories in the current directory that calls itself on each of those directories in turn, and so on, adding to the overall list of directories that gets returned at the end of the recursion.

The Recall() function would seem the ideal candidate for this, but I've never really got my head round how one writes a recursive function that adds to the final output each time it is called.

How would one modify this function:

list.dirs <- function(path) {
    x <- dir(path, full.names = TRUE)
    dnames <- x[file_test("-d", x)]
    dnames
}

To have it descend recursively through the directories in dnames adding any directories it finds to a list of all directories found within the dnames directories, and so on...?


Here is one way:

list.dirs <- function(path) {
     x <- dir(path, full.names = TRUE)
     dnames <- x[file_test("-d", x)]
    tmp <- character(0)
    for(i in seq_along(dnames) ) {
        tmp <- c(tmp, Recall(dnames[i]) )
    }
     c(dnames,tmp)
 } 

This just tacks the subdirectories onto the end, some different logic could be used to give a different ordering.

0

精彩评论

暂无评论...
验证码 换一张
取 消