split file names into list of lists in r

I have a bunch of csv file names that I need to read into R and split into a list of lists based on the file name. Say my files are named:

"gam_1-1.csv"
"gam_1-2.csv"
"gam_2-1.csv"
"gam_2-2.csv"

How do I separate them so that I have a list of lists with the file names, where:

list1 <- list("gam_1-1.csv","gam_1-2.csv")
list2 <- list("gam_2-1.csv","gam_2-2.csv")
final_list <- list(list1,list2)

>Solution :

You can split on a substring of the filenames.

files <- c("gam_1-1.csv", "gam_1-2.csv", "gam_2-1.csv", "gam_2-2.csv")
split(files, sub("-.*", "", files))
# $gam_1
# [1] "gam_1-1.csv" "gam_1-2.csv"
# $gam_2
# [1] "gam_2-1.csv" "gam_2-2.csv"

Leave a Reply