Representing a directory tree as a recursive list

I am stuck with a specific task. What I want is a function that, given the directory path, will return a recursive list as output.

The output should be in the form myList $ dir $ subdir $ subdir $ fullFilePath

So basically I want to present the directory tree as a specific list. I get all the files, I get all the subdirectories for each of the files, but I was fixated on how to list all this in a list with several levels.

+7
source share
2 answers

Here is a solution using recursion:

tree.list <- function(file.or.dir) { isdir <- file.info(file.or.dir)$isdir if (!isdir) { out <- file.or.dir } else { files <- list.files(file.or.dir, full.names = TRUE, include.dirs = TRUE) out <- lapply(files, tree.list) names(out) <- basename(files) } out } 

I tested it here in a small directory

 test.dir <- tree.list("./test") test.dir # $a # $a$`1.txt` # [1] "./test/a/1.txt" # # $a$aa # $a$aa$`2.txt` # [1] "./test/a/aa/2.txt" # # $b # $b$`3.txt` # [1] "./test/b/3.txt" 

If this is too slow for your needs, I would look at all the files in one call to list.files using recursive = TRUE , and then do a little parsing.

+5
source

Here is an ugly hack.

 mypath <- 'a/b/c/d' makelist <- function(filepath, fsep = '/'){ unlisted <- unlist(strsplit(filepath, fsep)) nsubs <- length(unlisted) mylistcall <- paste(paste(rep('list(', nsubs), unlisted, collapse = '='), '= NULL', paste(rep(')', nsubs), collapse = '')) mylist <- eval(parse(text = mylistcall)) return(mylist) } makelist(mypath) $a $a$b $a$b$c $a$b$c$d NULL 

Remembering

 fortune(106) If the answer is parse() you should usually rethink the question. -- Thomas Lumley R-help (February 2005) 

In this case, however, I would say that I must reconsider the answer.

+2
source

All Articles