Sign in

Post hoc

Post-hoc multiple comparisons: Tukey Honestly Significant Difference and Bonferroni

Pairwise comparisons of group means after an ANOVA, with the cutoff adjusted so the chance of any false alarm in the whole set stays at alpha.

Overview

ANOVA tells you that the group means are not all equal. It does not say which groups differ. The natural next step is to compare every pair, but each comparison is another chance for a false alarm, and with kk groups there are k(k−1)/2k(k-1)/2 pairs. Post-hoc tests keep the family-wise error rate, the chance of at least one false alarm across all pairs, at α\alpha. Bonferroni does it bluntly, by multiplying every pair's p-value by the number of pairs. Tukey's HSD (honestly significant difference) does it exactly for the all-pairs case, by using the distribution of the largest gap among kk means. Both estimate noise with the pooled within-group mean square from the ANOVA.

A short history

A significant ANOVA says that some means differ but not which. John Tukey answered this in 1949 with a procedure based on the studentised range, later known as the honestly significant difference, which keeps the error rate for the whole set of pairwise comparisons at alpha. The Bonferroni correction rests on inequalities published by Carlo Emilio Bonferroni in 1936; Olive Jean Dunn showed in 1961 how to apply it to multiple comparisons.

How it works

  1. Compute every group mean and the pooled within-group mean square MSWMS_W with N−kN-k degrees of freedom.
  2. For each pair, take the difference of the two means and its standard error from MSWMS_W and the two group sizes.
  3. Tukey: divide the absolute difference by the standard error to get qq and take the p-value from the studentized range distribution for kk means.
  4. Bonferroni: form an ordinary pooled tt statistic and multiply its two-sided p-value by the number of pairs, capping at 1.
  5. Build a simultaneous confidence interval for each difference from the method's critical value.
  6. Mark a pair as different when its adjusted p-value is below α\alpha, which is the same as its interval excluding zero.

Watch out for

  • Bonferroni is conservative: with many pairs the cutoff becomes so strict that real differences are missed. For all pairs Tukey is tighter.
  • Both methods pool one variance across all groups. If one group is far noisier, the standard error is wrong for every pair that involves it.
  • The template finds studentized range probabilities by numerical integration on a fixed grid, which is accurate enough for teaching but is not a replacement for a statistics library's tables at extreme tails.
  • Results can look inconsistent, for example A equals B and B equals C but A differs from C. That is a statement about evidence, not about equality.

Use cases

When to use it

After a significant ANOVA, when you need to say which specific groups differ. Use Tukey for all pairwise comparisons and Bonferroni when you care about only a few planned ones.

In industry

Clinical research
After a trial with several dose groups shows an overall effect, pairwise comparisons with adjusted cutoffs identify which doses differ from each other.
Agriculture
Variety trials report Tukey groupings, so that growers can see which varieties are statistically indistinguishable.
Genomics
Studies that test many genes or variants use Bonferroni style thresholds, such as the genome wide significance level, to limit false discoveries.

Choosing it: what must hold

  • A set of group means to compare, normally after an ANOVA on the same data.
  • For Tukey HSD, all pairwise comparisons with roughly equal variances; the Tukey-Kramer form handles unequal group sizes.
  • For Bonferroni, a known number of planned comparisons, ideally small.
  • Agreement that controlling the chance of any false alarm in the family is the right goal.

When to choose something else

IfUse instead
Every group is compared only with a controlDunnett's test
Variances are unequal across groupsThe Games-Howell procedure
There are hundreds or thousands of tests and some false positives are tolerableFalse discovery rate control with Benjamini-Hochberg
You want more power than Bonferroni for the same guaranteeThe Holm step down procedure

Math foundations

  1. Number of comparisons and the problem

    m=k(k−1)2,P(at least one false rejection)≤m αm = \frac{k(k-1)}{2}, \qquad P(\text{at least one false rejection}) \le m\,\alpha

    With kk groups there are mm pairs. If each is tested at level α\alpha, the chance of some false alarm can be as large as mαm\alpha. Both methods exist to pull this back down to α\alpha.

  2. Pooled noise estimate

    MSW=1N−k∑i=1k∑j=1ni(yij−yˉi)2MS_W = \frac{1}{N-k}\sum_{i=1}^{k}\sum_{j=1}^{n_i}(y_{ij}-\bar{y}_i)^2

    The within-group mean square from the ANOVA table. Every pairwise comparison uses it, so each one borrows information about the noise from all groups.

  3. Bonferroni

    tij=yˉi−yˉjMSW(1ni+1nj),pijadj=min⁡ ⁣(1, m pij)t_{ij} = \frac{\bar{y}_i-\bar{y}_j}{\sqrt{MS_W\left(\frac{1}{n_i}+\frac{1}{n_j}\right)}}, \qquad p^{\text{adj}}_{ij} = \min\!\big(1,\ m\,p_{ij}\big)

    An ordinary tt statistic on N−kN-k degrees of freedom, with its two-sided p-value pijp_{ij} multiplied by the number of pairs. This is the same as testing each pair at level α/m\alpha/m.

  4. Tukey's statistic

    qij=∣yˉi−yˉj∣MSW2(1ni+1nj)q_{ij} = \frac{\lvert\bar{y}_i-\bar{y}_j\rvert}{\sqrt{\frac{MS_W}{2}\left(\frac{1}{n_i}+\frac{1}{n_j}\right)}}

    The gap between two means in units of the standard error of a single mean. With equal sizes nn the denominator is MSW/n\sqrt{MS_W/n}. With unequal sizes this is the Tukey-Kramer form. Note that q=2 ∣t∣q = \sqrt{2}\,\lvert t\rvert.

  5. Tukey's reference distribution

    pijadj=P ⁣(Qk, N−k≥qij),Qk,ν=max⁡izˉi−min⁡izˉis/np^{\text{adj}}_{ij} = P\!\left(Q_{k,\,N-k} \ge q_{ij}\right), \qquad Q_{k,\nu} = \frac{\max_i \bar{z}_i - \min_i \bar{z}_i}{s/\sqrt{n}}

    QQ is the studentized range: the largest gap among kk sample means from one population, over an independent estimate of their standard error. Comparing every pair with the largest possible gap is what controls the error rate over all pairs at once.

  6. Simultaneous intervals

    (yˉi−yˉj)±c⋅SEij(\bar{y}_i-\bar{y}_j) \pm c \cdot SE_{ij}

    Here cc is the method's critical value and SEijSE_{ij} the matching denominator above. For Tukey cc is the 1−α1-\alpha quantile of QQ, for Bonferroni the 1−α/(2m)1-\alpha/(2m) quantile of tt. All mm intervals cover their true differences together with probability about 1−α1-\alpha.

Symbols

kk
number of groups
mm
number of pairwise comparisons
nin_i
size of group i
NN
total number of values
yˉi\bar{y}_i
mean of group i
MSWMS_W
within-group mean square
tij, qijt_{ij},\ q_{ij}
Bonferroni and Tukey statistics for the pair (i, j)
pijp_{ij}
unadjusted two-sided p-value of the pair
Qk,νQ_{k,\nu}
studentized range of k means with error degrees of freedom nu
zˉi, s\bar{z}_i,\ s
sample means from one common population and an independent estimate of its standard deviation
c, SEijc,\ SE_{ij}
critical value and standard error used in the interval
α\alpha
family-wise significance level

Worked by hand

Three groups of three: (1,2,3)(1,2,3), (2,3,4)(2,3,4), (6,7,8)(6,7,8) with means 2, 3, 7. From the one-way ANOVA, MSW=1MS_W = 1 on 6 degrees of freedom. The 5% critical value of the studentized range for 3 means and 6 degrees of freedom is 4.34.

SE=12(13+13)=13=0.577SE = \sqrt{\frac{1}{2}\left(\frac{1}{3}+\frac{1}{3}\right)} = \sqrt{\tfrac{1}{3}} = 0.577
q12=∣2−3∣0.577=1.73q_{12} = \frac{\lvert 2-3\rvert}{0.577} = 1.73
q13=∣2−7∣0.577=8.66,q23=∣3−7∣0.577=6.93q_{13} = \frac{\lvert 2-7\rvert}{0.577} = 8.66, \qquad q_{23} = \frac{\lvert 3-7\rvert}{0.577} = 6.93
smallest significant gap=4.34×0.577=2.51\text{smallest significant gap} = 4.34 \times 0.577 = 2.51

Groups 1 and 2 are not distinguishable (1.73<4.341.73 < 4.34). Group 3 differs from both. Any two means more than 2.51 apart are declared different.

Visual example

Loading the example.

Try this

  • Switch between Tukey HSD and Bonferroni and compare the critical gap in the readout.
  • Raise the number of groups from 3 to 5 with the same spacing: every interval widens.
  • Set the distance between means to 0. Any pair that is still flagged is a false alarm.

Code sample

from impl import PostHoc
from config import PostHocConfig

groups = [[6, 8, 4, 5, 3, 4], [8, 12, 9, 11, 6, 8], [13, 9, 11, 8, 7, 12]]
result = PostHoc(PostHocConfig(method="tukey", alpha=0.05)).fit(groups)
for c in result["comparisons"]:
    print(c["i"], c["j"], round(c["mean_diff"], 2), round(c["p_value"], 4), c["reject"])
Read the implementation (185 lines)
"""Post-hoc pairwise comparisons after a one-way ANOVA: Tukey's HSD and Bonferroni.

NumPy and the standard library only. Student's t comes from the regularized incomplete beta function and the
studentized range distribution from numerical integration, both defined in this file.
"""
from __future__ import annotations

import functools
import math

import numpy as np

try:
    from .config import PostHocConfig
except ImportError:  # run from the template's own folder
    from config import PostHocConfig

def _betacf(a: float, b: float, x: float) -> float:
    """Continued fraction of the incomplete beta function (modified Lentz method)."""
    tiny = 1e-300
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    d = 1.0 / (d if abs(d) > tiny else tiny)
    h = d
    for m in range(1, 2000):
        m2 = 2 * m
        for aa in (
            m * (b - m) * x / ((qam + m2) * (a + m2)),
            -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)),
        ):
            d = 1.0 + aa * d
            d = 1.0 / (d if abs(d) > tiny else tiny)
            c = 1.0 + aa / c
            c = c if abs(c) > tiny else tiny
            delta = d * c
            h *= delta
        if abs(delta - 1.0) < 1e-15:
            break
    return h


def betainc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b), for a, b > 0 and 0 <= x <= 1."""
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        return front * _betacf(a, b, x) / a
    return 1.0 - front * _betacf(b, a, 1.0 - x) / b

def t_cdf(t: float, df: float) -> float:
    """P(T <= t) for Student's t with `df` degrees of freedom."""
    tail = 0.5 * betainc(0.5 * df, 0.5, df / (df + t * t))
    return 1.0 - tail if t > 0 else tail


def t_sf(t: float, df: float) -> float:
    """P(T > t) for Student's t with `df` degrees of freedom."""
    return t_cdf(-t, df)

def _bisect(fn, lo: float, hi: float) -> float:
    """Root of the increasing function `fn` on [lo, hi], by bisection."""
    for _ in range(100):
        mid = 0.5 * (lo + hi)
        if fn(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)

def t_ppf(p: float, df: float) -> float:
    """Quantile of Student's t: the t with P(T <= t) = p, for 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError(f"p must be in (0, 1), got {p}")
    if p > 0.5:
        return -t_ppf(1.0 - p, df)
    lo = -1.0
    while t_cdf(lo, df) > p:
        lo *= 2.0
    return _bisect(lambda t: t_cdf(t, df) - p, lo, 0.0)

_Z = np.linspace(-8.0, 8.0, 321)  # integration grid for a standard normal value
_Z_WEIGHT = np.exp(-0.5 * _Z**2) / math.sqrt(2.0 * math.pi) * (_Z[1] - _Z[0])
_PHI_X = np.linspace(-14.0, 14.0, 28001)  # lookup table of the normal CDF, interpolated linearly
_PHI_Y = np.array([0.5 * math.erfc(-v / math.sqrt(2.0)) for v in _PHI_X])
_PHI_Z = np.interp(_Z, _PHI_X, _PHI_Y)  # the normal CDF on the integration grid


def _normal_range_cdf(w: np.ndarray, k: int) -> np.ndarray:
    """P(max - min of k independent standard normals <= w). w: (m,), returns (m,).

    Uses P = k * integral of pdf(z) * (cdf(z) - cdf(z - w))^(k - 1) dz, where z is the largest value.
    """
    spread = _PHI_Z[None, :] - np.interp(_Z[None, :] - w[:, None], _PHI_X, _PHI_Y)  # (m, len(_Z))
    return k * (spread ** (k - 1)) @ _Z_WEIGHT


def studentized_range_cdf(q: float, k: int, df: float) -> float:
    """P(Q <= q) for the studentized range of k means with `df` error degrees of freedom.

    Q = (largest mean - smallest mean) / (s / sqrt(n)). The normal range CDF is averaged over the
    distribution of s / sigma, which is sqrt(chi-square(df) / df).
    """
    if q <= 0.0:
        return 0.0
    half_width = 12.0 / math.sqrt(2.0 * df)
    s = np.linspace(max(1e-9, 1.0 - half_width), 1.0 + half_width, 101)
    log_density = (0.5 * df * math.log(df) - math.lgamma(0.5 * df) - (0.5 * df - 1.0) * math.log(2.0)
                   + (df - 1.0) * np.log(s) - 0.5 * df * s * s)
    y = np.exp(log_density) * _normal_range_cdf(q * s, k)
    return float(min(1.0, np.sum(0.5 * (y[1:] + y[:-1])) * (s[1] - s[0])))


@functools.lru_cache(maxsize=256)
def studentized_range_ppf(p: float, k: int, df: float) -> float:
    """The q with P(Q <= q) = p: the critical value found in studentized range tables."""
    if not 0.0 < p < 1.0:
        raise ValueError(f"p must be in (0, 1), got {p}")
    lo, hi = 0.0, 8.0
    while studentized_range_cdf(hi, k, df) < p:
        hi *= 2.0
    for _ in range(50):
        mid = 0.5 * (lo + hi)
        if studentized_range_cdf(mid, k, df) < p:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)

class PostHoc:
    """Compares every pair of group means while keeping the family-wise error rate at alpha."""

    def __init__(self, config: PostHocConfig | None = None) -> None:
        self.config = config or PostHocConfig()

    def fit(self, groups) -> dict:
        """Compare all pairs.

        groups: a sequence of k >= 2 one-dimensional samples, shapes (n_1,), ..., (n_k,).
        Returns a dict with `ms_within`, `df_within`, `critical_value` (of q for Tukey, of |t| for
        Bonferroni) and `comparisons`: one dict per pair i < j with `i`, `j`, `mean_diff`
        (mean_i - mean_j), `statistic`, `p_value` (already adjusted), `ci_low`, `ci_high` (simultaneous
        1 - alpha interval for the difference) and `reject`.
        """
        samples = [np.asarray(g, dtype=float).ravel() for g in groups]
        k = len(samples)
        if k < 2:
            raise ValueError("need at least 2 groups")
        if any(s.size < 2 for s in samples):
            raise ValueError("every group needs at least 2 values")
        sizes = [s.size for s in samples]
        means = [float(s.mean()) for s in samples]
        df = sum(sizes) - k
        ms_within = float(sum(np.sum((s - m) ** 2) for s, m in zip(samples, means))) / df
        if ms_within <= 0.0:
            raise ValueError("the within-group variance is zero, nothing to compare against")
        n_pairs = k * (k - 1) // 2
        alpha = self.config.alpha
        tukey = self.config.method == "tukey"
        critical = studentized_range_ppf(1.0 - alpha, k, df) if tukey else t_ppf(1.0 - alpha / (2 * n_pairs), df)
        comparisons = []
        for i in range(k):
            for j in range(i + 1, k):
                diff = means[i] - means[j]
                spread = ms_within * (1.0 / sizes[i] + 1.0 / sizes[j])
                if tukey:
                    se = math.sqrt(spread / 2.0)
                    stat = abs(diff) / se
                    p = 1.0 - studentized_range_cdf(stat, k, df)
                else:
                    se = math.sqrt(spread)
                    stat = diff / se
                    p = min(1.0, n_pairs * 2.0 * t_cdf(-abs(stat), df))
                comparisons.append({
                    "i": i, "j": j, "mean_diff": diff, "statistic": stat, "p_value": max(p, 0.0),
                    "ci_low": diff - critical * se, "ci_high": diff + critical * se,
                    "reject": p < alpha,
                })
        return {"method": self.config.method, "ms_within": ms_within, "df_within": df,
                "critical_value": critical, "comparisons": comparisons}
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Call PostHoc().fit(groups) on the three groups from the worked example and compare each statistic and the critical_value with the hand calculation. Then refit with PostHocConfig(method="bonferroni") and compare the adjusted p_value and the width of ci_low to ci_high for each pair between the two methods.

Check on learning

  1. With 10 groups, how many pairs are there and what per-pair level does Bonferroni use at α=0.05\alpha = 0.05? What does that do to the power to detect a moderate difference?
    A way to think about it

    Compute mm and α/m\alpha/m, then think about how far out in the tail of the tt distribution that cutoff sits.

  2. Why does Tukey's method refer each pair to the distribution of the largest gap among all kk means, even for a pair whose gap is small?
    A way to think about it

    The guarantee is about the whole family. If the largest gap rarely exceeds the cutoff by chance, ask what that implies for every smaller gap.

  3. You planned in advance to compare only two specific pairs out of ten groups. Which method is likely to give narrower intervals, and why?
    A way to think about it

    Bonferroni pays for the number of comparisons you actually make. Tukey always pays for all of them.

  4. An ANOVA is significant but no Tukey pair is. Is one of the two results wrong?
    A way to think about it

    The FF test responds to any pattern among the means, including contrasts such as one group against the average of the rest. Pairwise tests look only at pairs.