【问题标题】:Extract residuals from models fit in purrr从适合 purrr 的模型中提取残差
【发布时间】:2020-02-18 23:05:06
【问题描述】:

我对我的数据进行了分组,并为每个组拟合了一个模型,我希望得到每个组的残差。我可以使用 RStudio 的查看器查看每个模型的残差,但我不知道如何提取它们。提取一组残差可以像 diamond_mods[[3]][[1]][["residuals"]] 一样完成,但是我如何使用 purrr 从每个组中提取一组残差(连同扫帚一起得到一个漂亮的小标题)?

下面是我已经走了多远:

library(tidyverse)
library(purrr)
library(broom)


fit_mod <- function(df) {
  lm(price ~ poly(carat, 2, raw = TRUE), data = df)
}

diamond_mods <- diamonds %>%
  group_by(cut) %>%
  nest() %>%
  mutate(
    model = map(data, fit_mod),
    tidied = map(model, tidy)
    #resid = map_dbl(model, "residuals") #this was my best try, it doesn't work
  ) %>%
  unnest(tidied) 

【问题讨论】:

    标签: r dplyr purrr broom


    【解决方案1】:

    你很接近 - 但你应该使用 map() 而不是 map_dbl() 因为你需要返回一个列表而不是一个向量。

    diamond_mods <- diamonds %>%
      group_by(cut) %>%
      nest() %>%
      mutate(
        model = map(data, fit_mod),
        tidied = map(model, tidy),
        resid = map(model, residuals)
      ) 
    

    【讨论】:

      【解决方案2】:

      使用dplyrdevel 版本,我们可以在按'cut'分组后在condense 中执行此操作

      library(dplyr)
      library(ggplot2)
      library(broom)
      diamonds %>%
         group_by(cut) %>%
         condense(model = fit_mod(cur_data()),
                  tidied = tidy(model), 
                  resid = model[["residuals"]])
      # A tibble: 5 x 4
      # Rowwise:  cut
      #  cut       model  tidied           resid         
      #  <ord>     <list> <list>           <list>        
      #1 Fair      <lm>   <tibble [3 × 5]> <dbl [1,610]> 
      #2 Good      <lm>   <tibble [3 × 5]> <dbl [4,906]> 
      #3 Very Good <lm>   <tibble [3 × 5]> <dbl [12,082]>
      #4 Premium   <lm>   <tibble [3 × 5]> <dbl [13,791]>
      #5 Ideal     <lm>   <tibble [3 × 5]> <dbl [21,551]>
      

      【讨论】:

      • 我得去看看condense()。直到现在我才知道这个发展。
      • @jazzurro 现在,它比多次调用map 要容易得多,因为这与tibble 具有相似的行为,我们可以通过名称调用先前创建的列
      • 是的,这真的很有用。我猜这将在下一次更新中出现?明天我会花时间把这个功能拿起来。
      • @jazzurro 它将在下一个版本中。此外,summarise_at/muttate_at 等已被弃用以代替 summarise/mutate/filteracross
      • 哇,真的吗?这对我来说似乎是一个很大的变化。我需要根据此更改更改我的代码。谢谢你。
      猜你喜欢
      • 2020-05-12
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      相关资源
      最近更新 更多