Skip to contents

Testing pairwise differences

In the previous tutorial, we computed estimated marginal means for the three Species levels in the iris dataset. Often, however, we also want to statistically test the differences between those levels, which can be done using contrast analysis. Although this framework is much more general, its goal is analogous to traditional post hoc analyses (such as pairwise t-tests), which are widely used to follow up on omnibus tests (like ANOVAs) with specific pairwise comparisons.

Let’s start with the simple linear model from the previous tutorial:

library(ggplot2)
library(modelbased)
data(iris)

model <- lm(Sepal.Width ~ Species, data = iris)
means <- estimate_means(model, by = "Species")

plot(means, point = list(width = 0.1)) +
  theme_minimal()

We can compute all pairwise differences using estimate_contrasts():

estimate_contrasts(model, contrast = "Species")
> Conditional Contrasts
> 
> Level1     | Level2     | Difference |   SE |         95% CI | t(147) |      p
> ------------------------------------------------------------------------------
> versicolor | setosa     |      -0.66 | 0.07 | [-0.79, -0.52] |  -9.69 | < .001
> virginica  | setosa     |      -0.45 | 0.07 | [-0.59, -0.32] |  -6.68 | < .001
> virginica  | versicolor |       0.20 | 0.07 | [ 0.07,  0.34] |   3.00 |  0.003
> 
> Variable predicted: Sepal.Width
> Predictors contrasted: Species
> Standard errors and confidence intervals are based on the delta method.
> p-values are uncorrected.

All three pairwise differences are statistically significant. (Note that p-values are uncorrected by default; you can apply multiple-testing corrections such as "tukey" or "holm" via the p_adjust argument.)

Complex models

Just like estimate_means(), contrast analysis can be applied to more complex models that include covariates or interactions:

model <- lm(Sepal.Width ~ Species * Petal.Width, data = iris)
contrasts <- estimate_contrasts(model, contrast = "Species")
contrasts
> Conditional Contrasts
> 
> Level1     | Level2     | Difference |   SE |         95% CI | t(144) |      p
> ------------------------------------------------------------------------------
> versicolor | setosa     |      -1.59 | 0.39 | [-2.37, -0.81] |  -4.04 | < .001
> virginica  | setosa     |      -1.77 | 0.41 | [-2.59, -0.96] |  -4.29 | < .001
> virginica  | versicolor |      -0.18 | 0.15 | [-0.47,  0.10] |  -1.27 |  0.205
> 
> Variable predicted: Sepal.Width
> Predictors contrasted: Species
> Predictors held at: Petal.Width (1.2)
> Standard errors and confidence intervals are based on the delta method.
> p-values are uncorrected.

By default (estimate = "typical"), estimate_contrasts() evaluates the species differences at the mean value of Petal.Width (1.2). At this average petal width, the difference between virginica and versicolor changes sign and is no longer statistically significant.

We can visualize these means and pairwise contrasts together using a lighthouse plot:

plot(contrasts, estimate_means(model, by = "Species")) +
  theme_minimal()

The black points and vertical bars show the estimated means and their 95% confidence intervals, while the grey shaded beams show the 95% confidence intervals of the pairwise differences relative to each group mean. As a rule of thumb, if an entire beam slopes strictly upward or downward (meaning both the lower and upper bounds of the difference have the same sign), that pairwise difference is statistically significant.

Changes in differences across a continuous moderator

When a categorical predictor interacts with a continuous variable, we can also examine how the pairwise contrasts change across the range of that moderator. Using our interaction model above, we compute the species contrasts across 100 equally spaced values of Petal.Width and visualize the resulting trajectories:

contrasts <- estimate_contrasts(
  model,
  contrast = "Species",
  by = "Petal.Width",
  length = 100,
  # we use emmeans here because marginaleffects limits grid size
  # for pairwise comparisons by default
  backend = "emmeans"
)

# Create a label combining the two contrasted levels
contrasts$Contrast <- paste(contrasts$Level1, "-", contrasts$Level2)

# Visualize how the differences vary across Petal.Width
ggplot(contrasts, aes(x = Petal.Width, y = Difference)) +
  geom_ribbon(aes(fill = Contrast, ymin = CI_low, ymax = CI_high), alpha = 0.2) +
  geom_line(aes(colour = Contrast), linewidth = 1) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_minimal() +
  ylab("Difference")

As Petal.Width increases, the difference between virginica and versicolor (blue line) reverses direction—from slightly positive at very small petal widths to clearly negative (and statistically distinct from zero) at larger petal widths.

Conclusion

Contrast analysis provides a unified, model-based way to test specific differences between group levels—whether unconditionally, adjusted for covariates, or conditional on specific values of a moderator. For continuous predictors where you want to estimate slopes (rates of change) rather than discrete differences, see the companion tutorial on marginal effects (estimate_slopes()).