一个选项是转换为字符串,创建公式reformulate
并将其传递给lm
library(rlang)
library(purrr)
out2 <- map(myvars, ~ {
fmla <- reformulate(as_name(.x), 'mpg')
lm1 <- lm(fmla, data = mtcars)
lm1$call$formula <- fmla
lm1 })
-输出
out2
#[[1]]
#Call:
#lm(formula = mpg ~ cyl, data = mtcars)
#Coefficients:
#(Intercept) cyl
# 37.885 -2.876
#[[2]]
#Call:
#lm(formula = mpg ~ disp, data = mtcars)
#Coefficients:
#(Intercept) disp
# 29.59985 -0.04122
#[[3]]
#Call:
#lm(formula = mpg ~ hp, data = mtcars)
#Coefficients:
#(Intercept) hp
# 30.09886 -0.06823
- 检查 OP 的输出
out1 <- list(
lm(mpg ~ cyl, data = mtcars),
lm(mpg ~ disp, data = mtcars),
lm(mpg ~ hp, data = mtcars))
setequal(out1, out2)
#[1] TRUE