Skip to content

Instantly share code, notes, and snippets.

@TimTeaFan
Created January 30, 2023 17:22
Show Gist options
  • Save TimTeaFan/6324c446f5f95505ff86a014a33ae1c0 to your computer and use it in GitHub Desktop.
Save TimTeaFan/6324c446f5f95505ff86a014a33ae1c0 to your computer and use it in GitHub Desktop.
dplyr_workflow_compare_many_glm_models
library(tidyverse)
set.seed(123)
# some random dataa
my_dat <- tibble(
y = rbinom(300, 1, 0.5), # outcome 1
z = rbinom(300, 1, 0.5), # outcome 2
t = rbinom(300, 1, 0.5), # outcome 3
indep_var = runif(300), # this is our independet variable
x = sample(1:3, 300, replace = TRUE) # this is a grouping variable
)
# lets generate a meta data.frame containing all combinations ...
# ... of outcomes and groups of `x` and their models:
res <- tibble(dep = c("y", "z", "t")) %>%
expand_grid(x = c(1:3)) %>%
rowwise() %>%
mutate(mod = list(
glm(reformulate("indep_var", dep),
data = filter(my_dat, x == .env$x),
family = binomial)
)
)
# compare different outcome, groups of x and their models
res %>%
mutate(fit = broom::glance(mod),
.keep = "unused") %>%
unnest(fit)
# compare coefficients across different models
res %>%
summarise(dep,
x,
broom::tidy(mod)) %>%
filter(term != "(Intercept)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment