[SOLVED] Writing a function that returns a list with the name and content of subfolders in r

Issue

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!

Solution

Does this work?

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

Edit:
Suppose this is your current path :

path = "/Users/user/Desktop/task/Data"

You want to look into Folder_name (which is a folder inside path) and get the list of subfolders as well as their contents.

My_file <- function (Folder_name){
  newpath <- paste0(path, "/", Folder_name)
  lapply(list.files(newpath), function(i) list.files(paste0(newpath, "/", i)))
}

Try My_file("Data").

Answered By – slowowl

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.