如何根据条件从(嵌套)回归模型中绘制回归系数(或模型参数的其他估计值)?

时间:2017-07-29 12:54:19

标签: r plot ggplot2 regression broom

我正在尝试从(嵌套的)数据框(按条件)绘制回归系数,为每个条件下的嵌套数据运行四个条件(具有多个预测变量)的四个回归模型。绘制每个模型的每个模型的R-Squared值(参见示例)是有效的,但现在我想首先根据条件绘制回归系数x1(按x1降序为b),然后对x2绘制相同的回归系数(或者甚至是预测编号),有人可以帮我解决问题吗?

绘制多个模型的R - 平方值的示例:

# creating data example

library(modelr)
library(tidyverse)
set.seed(123)
data <- tibble(
condition = replicate(40, paste(sample(c("A", "B", "C", "D"), 1, replace=TRUE))),
x1 = rnorm(n = 40, mean = 10, sd = 2),
x2 = rnorm(n = 40, mean = 5, sd = 1.5),
y = x1*rnorm(n = 40, mean = 2, sd = 1) + x2*rnorm(n = 40, mean = 3, sd = 2))

by_condition <- data %>% 
  group_by(condition) %>% 
  nest()

# looking at data from first condition
by_condition$data[[1]]

# regression model function
reg.model <- function(df) {
    lm(y ~ x1 + x2,
    data = df)
}

# creating column with models per condition
by_condition <- by_condition %>% 
    mutate(model = map(data, reg.model))

# looking at reg. model for first group
by_condition$model[[1]]
summary(by_condition$model[[1]])

# graphing R-squared (ascending) per model by condition

glance <- by_condition %>%
  mutate(glance = map(model, broom::glance)) %>% 
  unnest(glance)

glance %>% 
  ggplot(aes(x = reorder(condition, desc(r.squared)), y = r.squared)) +
  geom_point() +
  coord_flip() +
  xlab("Condition") +
  ggtitle("R Square of reg. model per Condition")

所以这个例子有效,但我不知道如何分别提取系数,并按类似图中的条件按降序绘制。感谢

1 个答案:

答案 0 :(得分:0)

我找到了在不同条件下绘制(嵌套)回归模型系数的答案(整理踢屁股):

by_condition %>%
  mutate(regressions = map(model, broom::tidy)) %>% 
  unnest(regressions)

by_condition

regression_output <- by_condition %>%
  mutate(regressions = map(model, broom::tidy)) 

regression_coefficients <- regression_output %>% 
  unnest(regressions)

regression_coefficients %>% 
  ggplot(aes(x = term, y = estimate )) + 
  geom_point() +
  coord_flip() +
  facet_wrap(~ condition) +
  xlab("predictor") +
  ggtitle("Coefficients of reg. model per Condition")