Recursive function for defining folder structure in R

Viewed 72

Given a specific folder, I'd like to write a recursive function in R that returns a hierarchical list that matches the structure of the folder.

I have a function that achieves this, more or less, but I am wondering if there is a better way to do this?

# get_folder_str function -------------------------------------------------

library(stringr)
dir.create("~/Desktop/parent")
dir.create("~/Desktop/parent/child1")
dir.create("~/Desktop/parent/child2")
dir.create("~/Desktop/parent/child3")
dir.create("~/Desktop/parent/child2/grandchild1")
dir.create("~/Desktop/parent/child2/grandchild2")
file.create("~/Desktop/parent/child2/grandchild2/hello.txt")

get_folder_str <- function(root){
  root_files <- list.files(root)
  children <- str_c(root, root_files, sep = "/")
  folder_list <- list()
  for(i in 1:length(children)){
    if(children[i] == root){
     msg <- paste0(root, " is an empty folder")
     print(msg)
    }else{
      if(!dir.exists(children[i])){
        folder_list[[i]] <- children[i]
      } else{
####RECURSIVE BIT
        folder_list[[i]] <- get_folder_str(children[i])
       names(folder_list)[[i]] <- children[i]
      }
    }
  }
  folder_list
}


root <- "~/Desktop/parent"
get_folder_str(root = root)


###OUTPUT###

[1] "~/Desktop/parent/child1 is an empty folder"
[1] "~/Desktop/parent/child2/grandchild1 is an empty folder"
[1] "~/Desktop/parent/child3 is an empty folder"
$`~/Desktop/parent/child1`
list()

$`~/Desktop/parent/child2`
$`~/Desktop/parent/child2`$`~/Desktop/parent/child2/grandchild1`
list()

$`~/Desktop/parent/child2`$`~/Desktop/parent/child2/grandchild2`
$`~/Desktop/parent/child2`$`~/Desktop/parent/child2/grandchild2`[[1]]
[1] "~/Desktop/parent/child2/grandchild2/hello.txt"



$`~/Desktop/parent/child3`
list()
0 Answers
Related