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 中的练习,我尝试通过尝试使用 with()
评估 mtcars
环境中的 lm()
来解决练习 6,但它会引发错误.
为什么上次调用不起作用?
最佳答案
是环境问题。一种选择是引用
组件,这样它就不会被执行
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))
属性和调用
会有轻微的变化,但如果忽略它,
out1[[1]]$call <- out2[[1]]$call
all.equal(out1[[1]], out2[[1]], check.attributes = FALSE)
#[1] TRUE
关于r - 为什么在 map() 调用中使用 with() 作为函数在这个例子中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55894975/