Updating a linear regression model with update and purrr

江枫思渺然 提交于 2020-01-01 06:30:07

问题


I want to update a lm-model using the update-function inside a map-call, but this throws the following error:

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.

Can anyone help me with this problem? I am confused about this error, because e.g. this works totally fine:

mtcars %>% group_by(cyl) %>% 
  nest() %>% 
  mutate(lm1 = map(data, ~lm(mpg ~ wt, data = .x)), 
         lm2 = map_dbl(lm1, ~coefficients(.x)[1]))

回答1:


This is probably related to the environment where update is being evaluated. A simple workaround is to use map2 and explicitly reference the corresponding data:

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>


来源:https://stackoverflow.com/questions/47590037/updating-a-linear-regression-model-with-update-and-purrr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!