从适合 purrr 的模型中提取残差

Extract residuals from models fit in purrr

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

以下是我的进度:

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) 

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

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

使用 devel 版本的 dplyr,我们可以在按 '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]>