【发布时间】:2020-04-21 11:30:44
【问题描述】:
我正在尝试学习如何使用 R 中的 purrr 和 broom 包在数据集的子集上自动运行 3 个或更多回归模型。我正在使用 nest %>% mutate(map()) %>% unnest() 牢记在心。
当只有一个回归模型应用于多个数据子集时,我能够在线复制示例。但是,当我的函数中有多个回归模型时,我遇到了问题。
我想做什么
library(tidyverse)
library(broom)
estimate_model <- function(df) {
model1 <- lm(mpg ~ wt, data = df)
model2 <- lm(mpg ~ wt + gear, data = df)
model3 <- lm(mpg ~ wt + gear + vs, data = df)
}
ols_1dep_3specs <- mtcars %>%
nest(-cyl) %>%
mutate(
estimates = map(data, estimate_model), # want to run several models at once
coef_wt = map(estimate, ~pluck(coef(.), "wt")), # coefficient of wt only
se_wt = map(estimate, ~pluck(tidy(.), "std.error")[[2]]), # se of wt only
rsq = map(model, ~pluck(glance(.), "r.squared")),
arsq = map(model, ~pluck(glance(.), "adj.r.squared"))
) %>%
unnest(coef_wt, se_wt, rsq, arsq)
ols_1dep_3specs
不幸的是,这似乎只在函数estimate_model 仅包含一个回归模型时才有效。关于在有多个规范时如何编写代码的任何建议?对 nest() %>% mutate(map()) %>% nest() 框架之外的建议开放。
以下代码可以达到我希望达到的目的,但它涉及大量重复。
estimate_model1 <- function(df) {
model1 <- lm(mpg ~ wt, data = df)
}
estimate_model2 <- function(df) {
model2 <- lm(mpg ~ wt + gear, data = df)
}
estimate_model3 <- function(df) {
model3 <- lm(mpg ~ wt + gear + vs, data = df)
}
ols_1dep_3specs <- mtcars %>%
nest(-cyl) %>%
mutate(model_1 = map(data, estimate_model1),
model_2 = map(data, estimate_model2),
model_3 = map(data, estimate_model3)) %>%
mutate(coef_wt_1 = map_dbl(model_1, ~pluck(coef(.), "wt")),
coef_wt_2 = map_dbl(model_2, ~pluck(coef(.), "wt")),
coef_wt_3 = map_dbl(model_3, ~pluck(coef(.), "wt")),
rsq_1 = map_dbl(model_1, ~pluck(glance(.), "r.squared")),
rsq_2 = map_dbl(model_2, ~pluck(glance(.), "r.squared")),
rsq_3 = map_dbl(model_3, ~pluck(glance(.), "r.squared"))) %>%
dplyr::select(starts_with("coef_wt"), starts_with("rsq"))
【问题讨论】:
-
我认为在你的第一个函数中,返回
list(model1, model2, model3)
标签: r regression tidyverse purrr broom