I have a list of formulas, and I use lapply
and lm
to create a list of regression models. However, when I look at the call
component of each linear model, instead of seeing the explicit formula, I see the name of the variable I parsed into the linear model. E.g. using the mtcars dataset:
temp_formula_list = list(as.formula(hp~1),as.formula(hp~cyl))
temp_fm_list = lapply(temp_formula_list, function(x) lm(data = mtcars, formula = x))
Then examining the call
of temp_fm_list[[2]]
:
temp_fm_list[[2]]$call
gives
lm(formula = x, data = mtcars)
when I would like it to explicitly give
lm(formula = hp~cyl, data = mtcars)
You can do some simple computing on the language using bquote
to construct your call.
temp_fm_list = lapply(temp_formula_list, function(x) {
lmc <- bquote( lm(data = mtcars, formula = .(x)))
eval(lmc)
})
temp_fm_list
# Call:
# lm(formula = hp ~ 1, data = mtcars)
#
# Coefficients:
# (Intercept)
# 146.7
#
#
# [[2]]
#
# Call:
# lm(formula = hp ~ cyl, data = mtcars)
#
# Coefficients:
# (Intercept) cyl
# -51.05 31.96
Note that
function(x) do.call('lm', list(formula = x, data = quote(mtcars))
Would also work
Even with your original call you can recreate the formula from the terms
object associated with the model
eg
x <- hp ~ cyl
lmo <- lm(formula = x, data = mtcars)
formula(lmo)
## hp ~ cyl
lmo$call
# lm(formula = x, data = mtcars)
You can mess with this call
object if you wish (although this is rather dangerous practice)
# for example
lmo$call$formula <- x
lmo$call
## lm(formula = hp ~ cyl, data = mtcars)
## however you can create rubbish here too
lmo$call$formula <- 'complete garbage'
lmo$call
## lm(formula = "complete garbage", data = mtcars)
# but, being careful, you could use it appropriately
temp_fm_list = lapply(temp_formula_list, function(x) {
oo <- lm(data = mtcars, formula = x)
oo$call$formula <-x
oo
})
temp_fm_list
# Call:
# lm(formula = hp ~ 1, data = mtcars)
#
# Coefficients:
# (Intercept)
# 146.7
#
#
# [[2]]
#
# Call:
# lm(formula = hp ~ cyl, data = mtcars)
#
# Coefficients:
# (Intercept) cyl
# -51.05 31.96
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