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


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")


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:





Thank you!


Does this work?

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

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.