library(tidyverse)
formulas <- list(
mpg ~ disp,
mpg ~ I(1 / disp),
mpg ~ disp + wt,
mpg ~ I(1 / disp) + wt
)
# this works
map(formulas, ~ {lm(.x, mtcars)})
# this doesn't
map(formulas, ~ {with(mtcars, lm(.x))})
Error in eval(predvars, data, env) : object 'disp' not found
在https://adv-r.hadley.nz/functionals.html#exercises-28中的练习中,我尝试通过尝试使用lm()
在mtcars
环境中评估with()
来解决练习编号6,但抛出错误
为什么最后一次通话不起作用?
答案 0 :(得分:1)
这是环境问题。一种选择是quote
组件,这样就不会执行
formulas <- list(
quote(mpg ~ disp),
quote(mpg ~ I(1 / disp)),
quote(mpg ~ disp + wt),
quote(mpg ~ I(1 / disp) + wt)
)
out1 <- map(formulas, ~ with(mtcars, lm(eval(.x))))
out1
#[[1]]
#Call:
#lm(formula = eval(.x))
#Coefficients:
#(Intercept) disp
# 29.59985 -0.04122
#[[2]]
#Call:
#lm(formula = eval(.x))
#Coefficients:
#(Intercept) I(1/disp)
# 10.75 1557.67
#[[3]]
#Call:
#lm(formula = eval(.x))
#Coefficients:
#(Intercept) disp wt
# 34.96055 -0.01772 -3.35083
#[[4]]
#Call:
#lm(formula = eval(.x))
#Coefficients:
#(Intercept) I(1/disp) wt
# 19.024 1142.560 -1.798
它也应该使用第一种方法
out2 <- map(formulas, ~ lm(.x, mtcars))
属性和call
会稍有变化,但是如果忽略了
out1[[1]]$call <- out2[[1]]$call
all.equal(out1[[1]], out2[[1]], check.attributes = FALSE)
#[1] TRUE