为什么在此示例中,将with()用作map()调用中的函数不起作用?

时间:2019-04-28 22:09:32

标签: r purrr

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,但抛出错误

为什么最后一次通话不起作用?

1 个答案:

答案 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