if (requireNamespace("emmeans", quietly = TRUE)) {
# Data preparation
df <- ToothGrowth
df$dose <- as.factor(df$dose)
# Pairwise comparisons
res <- df %>%
group_by(supp) %>%
emmeans_test(len ~ dose, p.adjust.method = "bonferroni")
res
# Display estimated marginal means
attr(res, "emmeans")
# Show details
df %>%
group_by(supp) %>%
emmeans_test(len ~ dose, p.adjust.method = "bonferroni", detailed = TRUE)
# Marginal means averaged over another factor (e.g. a 2x3 design).
# Fit the full model and pass it with `model =` so that the estimated
# marginal means for `dose` are averaged over `supp` (instead of fitting
# `len ~ dose` alone, which would ignore `supp`):
model <- lm(len ~ supp * dose, data = df)
df %>% emmeans_test(len ~ dose, model = model)
# Repeated-measures / mixed designs: pass a fitted within-subject model
# (e.g. stats::aov() with an Error() term, or nlme::lme()) with `model =`:
# \donttest{
set.seed(123)
d <- data.frame(
id = factor(rep(1:10, 3)),
time = factor(rep(c("t1", "t2", "t3"), each = 10)),
score = rnorm(30)
)
rm_model <- stats::aov(score ~ time + Error(id / time), data = d)
d %>% emmeans_test(score ~ time, model = rm_model)
# }
}
Run the code above in your browser using DataLab