Home > Back-end >  Writing a function that returns a list with the name and content of subfolders in r
Writing a function that returns a list with the name and content of subfolders in r

Time:02-12

I'm trying to write a function that displays the subfolder names and contents. I have the following written code. However when I call the function, only the names of the subfolders are returned.

My_file <- function (Folder_name){

  My_list <- list.files(path =  "/Users/user/Desktop/task/Data/Data")
  
return(My_list)

}

The folder "Data" contains 2 subfolders "House" and "Cars". I want the function to return the name of the subfolder and the contents of each subfolder.

For example output should be:

$House 

Bungalow.extension

$Car 

Porsche.extension

Thank you!

CodePudding user response:

You can use recursive = TRUE in list.files -

My_file <- function (Folder_name) {
  My_list <- list.files(path = "/Users/user/Desktop/task/Data/Data", recursive = TRUE)
  return(My_list)
}

CodePudding user response:

Does this work?

path =  "/Users/user/Desktop/task/Data/Data"
lapply(list.files(path), function(i) list.files(paste0(path, "/", i)))
  • Related