【发布时间】: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)
【问题讨论】: