2

code below first prints out lm for mpg ~ disp then for mpg ~ disp + wt. I would like to create another loop over the models (note that the second lm is my personalize model, and for the simplicity, we can assume it is lm). how can I loop over different models?

data("mtcars")

formulas <- list(
  mpg ~ disp,
  mpg ~ disp + wt
)

    models <- list(lm, lm)
    
    res <- vector("list", length = length(formulas))
    
    for(i in seq_along(formulas)){
      res[[i]] <- lm(formulas[[i]], data = mtcars)
    
    }
    res
    
    or
    
    lapply(formulas, lm, data = mtcars)
Seyma Kalay
  • 2,037
  • 10
  • 22

3 Answers3

2

You may use nested lapply -

lapply(models, function(x) lapply(formulas, function(y) x(y, data = mtcars)))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

I like to use tidyverse's purrr for such multi-model approaches:

pacman::p_load(dplyr, purrr)
data("mtcars")

d <- crossing(formula = c(mpg ~ disp, mpg ~ disp + wt),
              model = list("lm", "glm")) %>% 
  
  mutate(result = pmap(.l = list(model, formula),
                       .f = function(m, f) do.call(m, args = list(formula = f, data = substitute(mtcars)))))
mzuba
  • 1,226
  • 1
  • 16
  • 33
2

We could use outer in base R and should be fast

out <- c(outer(models, formulas, Vectorize(function(x, y) list(x(y, data = mtcars)))))
akrun
  • 874,273
  • 37
  • 540
  • 662