Create multiple objects resulting from a loop of paste(list.files)

I have multiple folders such as "results/[model_name_here]/rasters/" and I’m trying to create multiple objects resulting from a loop of list.files. For example:

model_a <- list.files("results/rf/rasters", pattern = "tif$", full.names = TRUE)

I was trying to go for a for loop such as

models <- c("rf", "brt", "gam", "glm",
            "mars", "bart", "svm")

for(i in models){
     i <- list.files(paste0("results/", i, "/rasters/"), 
                                                           pattern = "tif$", full.names = TRUE)

But that doesn’t work properly. How can I proceed? I don’t mind using sapply or other type of function. The idea is simply to create, in my case, eight objects, each one called i in models

>Solution :

You want to initialize the result vector (which is a list) first, then in R we usually use the indices. Try this:

models <- c("rf", "brt", "gam", "glm", "mars", "bart", "svm")

r <- vector('list', length(models))
for (i in seq_along(models)) {
  r[[i]] <- list.files(paste0("results/", models[i], "/rasters/"), 
                       pattern="tif$", full.names=TRUE)

Leave a Reply