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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With