-1

我正在尝试从(嵌套)数据帧(按条件)绘制回归系数,为此我针对每个条件内的嵌套数据的四个条件(具有多个预测变量)运行四个回归模型。根据条件绘制每个模型的 R 平方值(参见示例)是可行的,但现在我想先按条件绘制 x1 的回归系数(x1 的 b 以降序排列),然后再绘制 x2 的回归系数(甚至由预测器编号),有人可以帮我解决代码吗?

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

# 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")

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

4

1 回答 1

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")
于 2017-07-30T13:53:47.600 回答