Using lapply to set multiple models - how to keep model formula standalone in lm object
The following code matches 4 different model formulas in the dataset mtcars
, using either for loop or lapply. In both cases, the formula stored in the result is called a formula formulas[[1]]
, formulas[[2]]
etc., and not a formula for a person.
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 a complete, readable formula in the result?
+3
source to share
2 answers
This should work
lapply(formulas, function(x, data) eval(bquote(lm(.(x),data))), data=mtcars)
And he extracts
[[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 lm
and then evaluate the expression.
+6
source to share
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 want the result names to have a symbolic version of formulas, it's just "
names(res) <- as.character(formulas)
res[1]
#-----
$`mpg ~ disp`
Call:
lm(formula = frm, data = mtcars)
Coefficients:
(Intercept) disp
29.59985 -0.04122
0
source to share