Skip to content

Instantly share code, notes, and snippets.

@cmrnp
Created October 27, 2021 06:16
Show Gist options
  • Save cmrnp/5ef279afe59a9b1f5ceea2a578355544 to your computer and use it in GitHub Desktop.
Save cmrnp/5ef279afe59a9b1f5ceea2a578355544 to your computer and use it in GitHub Desktop.
Tidyverse approach to fitting multiple models using data frame of formulas
library(tidyverse)
library(palmerpenguins) # for `penguins` data set
penguin_model_formulas <- tribble(
~name, ~formula,
"depth only", "bill_length_mm ~ bill_depth_mm",
"species only", "bill_length_mm ~ species",
"depth and species", "bill_length_mm ~ bill_depth_mm + species",
)
# fit a model for each formula listed above
penguin_models <- penguin_model_formulas %>%
rowwise(name, formula) %>%
summarise(model = list(lm(formula, data = penguins))) %>%
ungroup()
# regression coefficients
library(broom)
penguin_models %>%
rowwise(name) %>%
summarise(tidy(model, conf.int = TRUE)) %>%
ungroup()
# overall tests
library(emmeans)
penguin_models %>%
rowwise(name) %>%
summarise(joint_tests(model)) %>%
ungroup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment