r - 为什么在 map() 调用中使用 with() 作为函数在这个例子中不起作用?

标签 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 中的练习,我尝试通过尝试使用 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/

相关文章:

r - 让函数接受参数列表列

r - 在 R 中压平数据框中的列表列

r - 根据不同的条件过滤不同的变量

r - 使用 pmap() 计算几列的行均值

r - 泊松分布上的 MLE bootstrap

r - 设置 alpha 并删除 ggpairs 中密度图的黑色轮廓

r - 为绘图中的标题部分着色

r - 如何用 R 创建二元关系矩阵?

r - 在purrr::map中相当于 `break`

python - 尝试将 DataFrame 写入 Feather 时出错。 feather 是否支持列表列?