Is there a way to take a list of different files and group them together in a separate list based off identical characters on R?

Viewed 29

Is there a way to take a list of different files and group them together in a separate list based off identical characters on R?

So taking a list like:

list_of_files <- c("file1.tif", "file1.png", "file1.rds", "file2.tif", "file2.png")

And then ending up with a new variable that when called returns something like:

new_variable[1]
>>> "file1.tif" "file1.png" "file1.rds"

new_variable[2]
>>> "file2.tif" "file2.png"

Once again, I want to be able to group all of the files by identical characters in a particular spot. The one I am using is obviously not just called file1 and file2, but for simplicity's sake, those are the file names I created. And it is also more than just 2 different files so a simple if statement probably will not do.

1 Answers

Use split based on the files without extension into a list

out <- split(list_of_files, tools::file_path_sans_ext(list_of_files))
out
$file1
[1] "file1.tif" "file1.png" "file1.rds"

$file2
[1] "file2.tif" "file2.png"

and extract the list elements with $ or [[

out$file1
out[[1]]
Related