2

What is a good way to convert a directory structure to a nested list like the following? I would like each directory to be a list that can contain either single element entities (files) or sublists (other directories).

I was going to write a recursive function using list.dirs and list.files but figured there might be another way since this seems to be a common structure.

## example: make directories and files
## Note: this makes files in a folder called 'test' on your computer
dir.create("test")
for (i in 1:3) dir.create(file.path("test", paste0("sub dir", i)))
dir.create("test/sub dir1/sub sub dir")
writeLines("thing", "test/text.txt")
writeLines("thing1", "test/sub dir1/text.txt")
writeLines("thing2", "test/sub dir1/text1.txt")

## Hoping for a result like this, I guess it could be "" instead of list() for empty directories
res <- list(test=list(
              "text.txt",
              `sub dir1`=list(`sub sub dir`=list(), "text.txt", "text1.txt"),
              `sub dir2`=list(),
              `sub dir3`=list()
))

str(res)
# List of 1
#  $ test:List of 4
#   ..$         : chr "text.txt"
#   ..$ sub dir1:List of 3
#   .. ..$ sub sub dir: list()
#   .. ..$            : chr "text.txt"
#   .. ..$            : chr "text1.txt"
#   ..$ sub dir2: list()
#   ..$ sub dir3: list()
Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Possible duplicate of [Representing a directory tree as a recursive list](http://stackoverflow.com/questions/14188197/representing-a-directory-tree-as-a-recursive-list) – rawr Nov 30 '15 at 02:27

0 Answers0