Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Heisenberg Avatar asked Aug 14 '14 16:08

Heisenberg


2 Answers

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.

like image 179
MrFlick Avatar answered Sep 23 '22 13:09

MrFlick


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 
like image 43
IRTFM Avatar answered Sep 25 '22 13:09

IRTFM