Skip to content

Instantly share code, notes, and snippets.

@cmrnp
Last active October 27, 2021 06:06
Show Gist options
  • Save cmrnp/fccb6338b0fd207ac13137d9e0788e53 to your computer and use it in GitHub Desktop.
Save cmrnp/fccb6338b0fd207ac13137d9e0788e53 to your computer and use it in GitHub Desktop.
Tidyverse approach to fitting multiple models
library(tidyverse)
library(palmerpenguins) # for `penguins` data set
# fit a model for each variable (bill length, bill depth, flipper length)
penguin_models <- penguins %>%
pivot_longer(c(bill_length_mm, bill_depth_mm, flipper_length_mm),
names_to = "outcome_name",
values_to = "outcome") %>%
group_by(outcome_name) %>%
summarise(model = list(lm(outcome ~ species, data = cur_data())))
# regression coefficients
library(broom)
penguin_models %>%
rowwise(outcome_name) %>%
summarise(tidy(model, conf.int = TRUE))
# estimated means
library(emmeans)
penguin_models %>%
rowwise(outcome_name) %>%
summarise(emmeans(model, "species") %>%
as_tibble())
# pairwise comparisons
penguin_models %>%
rowwise(outcome_name) %>%
summarise(emmeans(model, "species") %>%
pairs(adjust = "none", infer = TRUE) %>%
as_tibble())
@cmrnp
Copy link
Author

cmrnp commented Oct 27, 2021

minor correction: cur_group() should be cur_data()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment