简体   繁体   中英

Using lapply to fit multiple model — how to keep the model formula self-contained in lm object

The following code fits 4 different model formulas to the mtcars dataset, using either for loop or lapply. In both cases, the formula stored in the result is referred to as formulas[[1]] , formulas[[2]] , etc. instead of the human-readable formula.

formulas <- list(
  mpg ~ disp,
  mpg ~ I(1 / disp),
  mpg ~ disp + wt,
  mpg ~ I(1 / disp) + wt
)
res <- vector("list", length=length(formulas))
for (i in seq_along(formulas)) {
  res[[i]] <- lm(formulas[[i]], data=mtcars)
}
res
lapply(formulas, lm, data=mtcars)

Is there a way to make the full, readable formula show up in the result?

This should work

lapply(formulas, function(x, data) eval(bquote(lm(.(x),data))), data=mtcars)

And it retruns

[[1]]

Call:
lm(formula = mpg ~ disp, data = data)

Coefficients:
(Intercept)         disp  
   29.59985     -0.04122  


[[2]]

Call:
lm(formula = mpg ~ I(1/disp), data = data)

Coefficients:
(Intercept)    I(1/disp)  
      10.75      1557.67  

....etc

We use bquote to insert the formula into the call to lm and then evaluate the expression.

Why not just:

lapply( formulas, function(frm) lm( frm, data=mtcars))
#------------------
[[1]]

Call:
lm(formula = frm, data = mtcars)

Coefficients:
(Intercept)         disp  
   29.59985     -0.04122  

[[2]]

Call:
lm(formula = frm, data = mtcars)

Coefficients:
(Intercept)    I(1/disp)  
      10.75      1557.67  
snpped....

If you wanted the names of the result to have the 'character'-ized version of the formulas it would just be"

 names(res) <- as.character(formulas)
 res[1]
#-----
$`mpg ~ disp`

Call:
lm(formula = frm, data = mtcars)

Coefficients:
(Intercept)         disp  
   29.59985     -0.04122 

you can also try something like

library(purrr)
library(tibble)
models <- map(formulas, lm, data = mtcars)
models

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM