我想使用lm
- 函数在update
- 调用内更新map
- 模型,但这会引发以下错误:
mtcars %>% group_by(cyl) %>%
nest() %>%
mutate(lm1 = map(data, ~lm(mpg ~ wt, data = .x)),
lm2 = map(lm1, ~update(object = .x, formula = .~ . + hp)))
Error in mutate_impl(.data, dots) :
Evaluation error: cannot coerce class ""lm"" to a data.frame.
任何人都可以帮我解决这个问题吗?我对此错误感到困惑,因为例如这完全没问题:
mtcars %>% group_by(cyl) %>%
nest() %>%
mutate(lm1 = map(data, ~lm(mpg ~ wt, data = .x)),
lm2 = map_dbl(lm1, ~coefficients(.x)[1]))
答案 0 :(得分:2)
这可能与正在评估update
的环境有关。一个简单的解决方法是使用map2
并显式引用相应的数据:
library(tidyverse)
mtcars %>% group_by(cyl) %>%
nest() %>%
mutate(lm1 = map(data, ~lm(mpg ~ wt, data = .x)),
lm2 = map2(lm1, data, ~update(object = .x, formula. = .~ . + hp,
data = .y)))
#> # A tibble: 3 x 4
#> cyl data lm1 lm2
#> <dbl> <list> <list> <list>
#> 1 6 <tibble [7 x 10]> <S3: lm> <S3: lm>
#> 2 4 <tibble [11 x 10]> <S3: lm> <S3: lm>
#> 3 8 <tibble [14 x 10]> <S3: lm> <S3: lm>