-1

I'm trying to plot regression coefficients from a (nested) dataframe (by condition) for which i ran four regression models for the four condtitions (with multiple predictors) on the nested data within each condition. Plotting the R-Squared values per model per condition (see example) works, but now I'd like to plot the regression coefficients first for x1 by condition (b's for x1 in descending order) and then same for x2 (or even facetted by predictor number), can someone help me out with the code?

Example of plotting R - Squared values for multiple models:

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

So this example works, but i don't know how to extract the coefficients seperately and plot those in descending order by condition in similar graphs. Thanks

Benjamin Telkamp
  • 1,451
  • 2
  • 17
  • 31

1 Answers1

0

I found the answer to plotting coefficients of (nested) regression models within different conditions (tidying kicks ass):

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")
Benjamin Telkamp
  • 1,451
  • 2
  • 17
  • 31