kath
kath

Reputation: 7724

Updating a linear regression model with update and purrr

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]))

Upvotes: 3

Views: 717

Answers (1)

Thomas K
Thomas K

Reputation: 3311

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>

Upvotes: 2

Related Questions