本文介绍了使用update和purrr更新线性回归模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在map调用中使用update函数更新lm模型,但这会引发以下错误:

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

推荐答案

这可能与正在评估update的环境有关.一个简单的解决方法是使用map2并显式引用相应的数据:

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>

这篇关于使用update和purrr更新线性回归模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 17:07