Sign in

ANCOVA

Analysis of Covariance

A comparison of group means after removing the part of the outcome that a numeric covariate explains, done with one linear model.

Overview

Groups often differ in something you did not set out to study. Students in one class may have started with higher scores, so comparing final scores alone mixes the teaching effect with the head start. ANCOVA (analysis of covariance) fits a straight line of the outcome against that starting variable, called the covariate, with the same slope in every group and a separate height for each group. Comparing the heights is comparing the groups at one common covariate value. This removes bias from unequal starting points, and it also removes covariate-driven noise, which makes the test sharper. The method rests on the slopes really being equal, and the template tests that too.

A short history

Ronald Fisher introduced the analysis of covariance in the early 1930s, in later editions of Statistical Methods for Research Workers, by combining his analysis of variance with regression. Agricultural experimenters needed to adjust yields for a measurement taken before treatment, such as the previous yield of a plot. Removing the variation explained by that covariate makes the comparison of treatments both fairer and more precise.

How it works

  1. Centre each covariate by subtracting its overall mean, so every group's intercept is its predicted outcome at the average covariate value.
  2. Fit the full model by least squares: one intercept per group plus common slopes for the covariates. Record its residual sum of squares.
  3. Fit a reduced model with one shared intercept. The rise in residual sum of squares measures the group effect.
  4. Fit another reduced model with no covariates. The rise in residual sum of squares measures the covariate effect.
  5. Turn each rise into an FF statistic against the full model's error mean square and read the p-value from the FF distribution.
  6. Report the group intercepts as adjusted means, and with check_slopes on, test a model with a separate slope per group against the common-slope model.

Watch out for

  • If the slopes differ between groups, a single adjusted difference does not exist because the gap depends on where you look, so check slope_homogeneity before reading the group test.
  • A covariate that the treatment itself changes will absorb part of the treatment effect, so use only covariates measured before or independently of the grouping.
  • When the groups barely overlap on the covariate, the adjusted means are extrapolations along the fitted line and depend entirely on the line being straight.
  • The relation between outcome and covariate is assumed linear. A curved relation leaves structure in the residuals and biases the adjustment.

Use cases

When to use it

Comparing groups on an outcome that also depends on a measured numeric variable, such as a baseline score or age, especially when the groups differ on that variable or it explains much of the noise.

In industry

Clinical trials
A trial comparing blood pressure treatments adjusts each patient's final reading for the baseline reading, which regulators such as the European Medicines Agency recommend for precision.
Education research
Studies comparing teaching methods adjust final test scores for a pre test, so that groups that started ahead are not credited with the method's effect.
Online experiments
A/B testing teams adjust a metric for each user's value before the experiment, a regression adjustment in the same spirit that reduces variance.

Choosing it: what must hold

  • A numeric outcome, one categorical factor and at least one numeric covariate measured before or independently of the treatment.
  • A roughly linear relation between covariate and outcome, with the same slope in every group.
  • Residuals that are roughly normal with similar variance across groups.
  • A covariate that the treatment cannot have affected.

When to choose something else

IfUse instead
There is no useful covariateOne-way ANOVA
The slopes differ between groupsA linear model with a group by covariate interaction
There are several outcome variablesMANOVA, or its covariate adjusted form MANCOVA
The same subjects are measured many timesA mixed effects model

Math foundations

  1. The model

    yij=μi+β (xij−xˉ)+εijy_{ij} = \mu_i + \beta\,(x_{ij}-\bar{x}) + \varepsilon_{ij}

    Each group has its own level μi\mu_i and all groups share one slope β\beta on the centred covariate. Because the covariate is centred, μi\mu_i is the group's expected outcome at the average covariate value.

  2. The common slope

    β^=∑i∑j(xij−xˉi)(yij−yˉi)∑i∑j(xij−xˉi)2\hat{\beta} = \frac{\sum_{i}\sum_{j}(x_{ij}-\bar{x}_i)(y_{ij}-\bar{y}_i)}{\sum_{i}\sum_{j}(x_{ij}-\bar{x}_i)^2}

    For one covariate, least squares gives the pooled within-group slope. Deviations are taken from each group's own means, so differences between groups do not leak into the slope.

  3. Adjusted means

    μ^i=yˉi−β^ (xˉi−xˉ)\hat{\mu}_i = \bar{y}_i - \hat{\beta}\,(\bar{x}_i - \bar{x})

    Slide each raw group mean along the common slope to the overall covariate mean. A group that started high on the covariate is moved down if the slope is positive, and the reverse.

  4. Testing by model comparison

    F=(RSSreduced−RSSfull)/qRSSfull/(N−k−c)F = \frac{(RSS_{\text{reduced}} - RSS_{\text{full}})/q}{RSS_{\text{full}}/(N-k-c)}

    Dropping terms from the model can only raise the residual sum of squares. The rise per dropped parameter, relative to the error mean square, follows an FF distribution with (q, N−k−c)(q,\ N-k-c) degrees of freedom when the dropped terms are truly zero. Here q=k−1q=k-1 for the group test and q=cq=c for the covariate test.

  5. Equal-slopes check

    Fslopes=(RSSfull−RSSseparate)/((k−1)c)RSSseparate/(N−k−kc)F_{\text{slopes}} = \frac{(RSS_{\text{full}} - RSS_{\text{separate}})/\big((k-1)c\big)}{RSS_{\text{separate}}/(N-k-kc)}

    The same comparison one level up: the common-slope model against a model with its own slope in each group. A small p-value says the slopes differ and the ANCOVA adjustment is not valid.

Symbols

yij, xijy_{ij},\ x_{ij}
outcome and covariate of observation j in group i
μi\mu_i
level of group i at the average covariate value (its adjusted mean)
β\beta
common within-group slope
xˉ, xˉi\bar{x},\ \bar{x}_i
overall and group means of the covariate
yˉi\bar{y}_i
raw mean of the outcome in group i
εij\varepsilon_{ij}
random noise
RSSRSS
residual sum of squares of a fitted model
N, k, cN,\ k,\ c
number of observations, groups and covariates
qq
number of parameters dropped in the reduced model

Worked by hand

Two groups of three. Group A has covariate x=(1,2,3)x=(1,2,3) and outcome y=(2,3,4)y=(2,3,4). Group B has x=(3,4,5)x=(3,4,5) and y=(5,6,7)y=(5,6,7). Group means: xˉA=2\bar{x}_A=2, yˉA=3\bar{y}_A=3, xˉB=4\bar{x}_B=4, yˉB=6\bar{y}_B=6, and xˉ=3\bar{x}=3.

β^=[(−1)(−1)+0+(1)(1)]+[(−1)(−1)+0+(1)(1)](1+0+1)+(1+0+1)=44=1\hat{\beta} = \frac{\left[(-1)(-1)+0+(1)(1)\right]+\left[(-1)(-1)+0+(1)(1)\right]}{(1+0+1)+(1+0+1)} = \frac{4}{4} = 1
μ^A=3−1⋅(2−3)=4\hat{\mu}_A = 3 - 1\cdot(2-3) = 4
μ^B=6−1⋅(4−3)=5\hat{\mu}_B = 6 - 1\cdot(4-3) = 5

The raw means differ by 3, but the adjusted means differ by only 1. Two thirds of the raw gap came from group B starting with higher covariate values. The points here lie exactly on lines to keep the arithmetic clean.

Visual example

Loading the example.

Try this

  • Set the true group effect to 0 and the head start to 4: the raw means differ a lot, the adjusted means do not.
  • Set the head start to 0 and raise the noise: compare the p-value with and without the covariate.
  • Move the extra slope in group B away from 0 and watch the equal slopes check fail.

Code sample

import numpy as np
from impl import Ancova
from config import AncovaConfig

rng = np.random.default_rng(0)
groups = np.repeat([0, 1, 2], 20)
baseline = rng.normal(5, 2, 60)
y = np.array([0.0, 1.0, 3.0])[groups] + 2.0 * baseline + rng.normal(0, 0.5, 60)
result = Ancova(AncovaConfig(alpha=0.05)).fit(y, groups, baseline)
print(result["group"]["f"], result["group"]["p_value"], result["adjusted_means"])
Read the implementation (133 lines)
"""ANCOVA: one-way analysis of covariance, fitted by least squares and tested by model comparison.

NumPy and the standard library only. The F tail probability comes from the regularized incomplete beta
function defined in this file.
"""
from __future__ import annotations

import math

import numpy as np

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

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 f_sf(f: float, df1: float, df2: float) -> float:
    """P(F > f) for an F variable with (`df1`, `df2`) degrees of freedom."""
    if f <= 0.0:
        return 1.0
    return betainc(0.5 * df2, 0.5 * df1, df2 / (df2 + df1 * f))


def f_cdf(f: float, df1: float, df2: float) -> float:
    """P(F <= f) for an F variable with (`df1`, `df2`) degrees of freedom."""
    return 1.0 - f_sf(f, df1, df2)

def _fit(design: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, float]:
    """Least squares. design: (n, p), y: (n,). Returns the coefficients (p,) and the residual sum of squares."""
    beta = np.linalg.lstsq(design, y, rcond=None)[0]
    return beta, float(np.sum((y - design @ beta) ** 2))


class Ancova:
    """Model: y = group intercept + covariates @ common slopes + noise."""

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

    def _f_test(self, rss_small: float, rss_full: float, df_num: float, df_den: float) -> dict:
        """F test that the terms dropped from the full model are zero."""
        ms_error = rss_full / df_den
        gain = max(rss_small - rss_full, 0.0)
        if ms_error > 1e-12 * max(rss_small, 1.0):
            f = (gain / df_num) / ms_error
        else:
            f = math.inf if gain > 1e-12 * max(rss_small, 1.0) else 0.0
        p = f_sf(f, df_num, df_den) if math.isfinite(f) else 0.0
        return {"ss": gain, "df": df_num, "f": f, "p_value": p, "reject": p < self.config.alpha}

    def fit(self, y, groups, covariates) -> dict:
        """Run the analysis.

        y:          outcome, shape (n,).
        groups:     group label of every observation, shape (n,), any hashable values.
        covariates: numeric covariate(s), shape (n,) or (n, c).
        Returns a dict with `group` and `covariate` (F tests, each with ss, df, f, p_value, reject),
        `slopes` (c,) the common within-group slopes, `labels` (k,), `raw_means` (k,),
        `adjusted_means` (k,) the group means at the overall covariate mean, `error` (ss, df, ms) and,
        when `check_slopes` is on, `slope_homogeneity` (an F test of the group x covariate interaction).
        """
        y = np.asarray(y, dtype=float).ravel()
        x = np.asarray(covariates, dtype=float)
        x = x.reshape(-1, 1) if x.ndim == 1 else x
        labels, codes = np.unique(np.asarray(groups), return_inverse=True)
        n, c, k = y.size, x.shape[1], labels.size
        if x.shape[0] != n or codes.size != n:
            raise ValueError("y, groups and covariates must have the same number of rows")
        if k < 2:
            raise ValueError("need at least 2 groups")
        if n - k - c <= 0:
            raise ValueError("not enough observations for the number of groups and covariates")
        dummies = (codes[:, None] == np.arange(k)[None, :]).astype(float)  # (n, k)
        xc = x - x.mean(axis=0)  # centred, so the group intercepts are the adjusted means
        beta, rss_full = _fit(np.hstack([dummies, xc]), y)
        _, rss_no_group = _fit(np.hstack([np.ones((n, 1)), xc]), y)
        _, rss_no_cov = _fit(dummies, y)
        df_error = n - k - c
        result = {
            "labels": labels,
            "group": self._f_test(rss_no_group, rss_full, k - 1, df_error),
            "covariate": self._f_test(rss_no_cov, rss_full, c, df_error),
            "slopes": beta[k:],
            "raw_means": dummies.T @ y / dummies.sum(axis=0),
            "adjusted_means": beta[:k],
            "error": {"ss": rss_full, "df": df_error, "ms": rss_full / df_error},
        }
        if self.config.check_slopes:
            df_inter = n - k - k * c
            if df_inter <= 0:
                raise ValueError("not enough observations to test slope homogeneity; set check_slopes=false")
            per_group = np.hstack([dummies[:, [g]] * xc for g in range(k)])  # a separate slope per group
            _, rss_separate = _fit(np.hstack([dummies, per_group]), y)
            result["slope_homogeneity"] = self._f_test(rss_full, rss_separate, (k - 1) * c, df_inter)
        return result
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Enter the worked example, add a little random noise to y, and call Ancova().fit(y, groups, covariates). Compare raw_means with adjusted_means and read slopes. Then change group B's outcome so its slope is 3 instead of 1, refit, and see what slope_homogeneity reports.

Check on learning

  1. In a randomised experiment the groups have nearly equal covariate means, so the adjustment barely moves the group means. Why can ANCOVA still give a much smaller p-value than one-way ANOVA?
    A way to think about it

    Look at the denominator of the FF statistic. Ask what happens to the residual sum of squares when the covariate explains much of the outcome.

  2. The slope is 2 in one group and 0 in the other. Describe what the difference between the groups looks like at low, middle and high covariate values, and why one adjusted difference cannot summarise it.
    A way to think about it

    Draw two lines with different slopes. The vertical gap between them is the group difference at each covariate value.

  3. A study adjusts a drug trial for blood pressure measured after treatment began. The drug works by lowering blood pressure. What does the adjusted group effect now measure?
    A way to think about it

    Adjusting compares patients at the same covariate value. Think about what is left of the drug's effect once you hold fixed the very thing it changes.

  4. Why does the template centre the covariate before fitting, and would the FF tests change if it did not?
    A way to think about it

    Centring changes what the intercepts mean, not the space of lines the model can fit. Compare the fitted values with and without centring.