Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading