Sign in

One way

One-way Analysis of Variance

A test of whether three or more group means are equal, made by comparing the spread between groups with the spread inside them.

Overview

Suppose you measure the same thing in several groups and the group averages differ. Some difference always appears by chance, because every group contains noisy values. One-way ANOVA (analysis of variance) asks whether the averages are further apart than that noise can explain. It splits the total variation into two parts: how far the group means sit from the overall mean, and how far single values sit from their own group mean. The ratio of the two, each divided by its degrees of freedom, is the F statistic. A ratio near 1 means the groups look alike, a large ratio means at least one mean stands apart.

A short history

Ronald Fisher developed the analysis of variance at Rothamsted Experimental Station in the early 1920s to compare crop yields under several fertiliser treatments, and set it out for a wide audience in Statistical Methods for Research Workers in 1925. Running many two group t tests inflates the chance of a false alarm. ANOVA answers with one test, the F ratio of variation between groups to variation within them, named in Fisher's honour by George Snedecor.

How it works

  1. Compute each group mean yˉi\bar{y}_i and the grand mean yˉ\bar{y} of all values together.
  2. Add up the between-group sum of squares: each group's squared distance from the grand mean, weighted by its size nin_i.
  3. Add up the within-group sum of squares: every value's squared distance from its own group mean.
  4. Divide each sum by its degrees of freedom, k−1k - 1 and N−kN - k, to get the two mean squares.
  5. Form FF as the between mean square over the within mean square.
  6. Read the p-value as the upper tail of the FF distribution with (k−1, N−k)(k-1,\, N-k) degrees of freedom and reject the null hypothesis when it is below α\alpha.

Watch out for

  • A significant FF says that some mean differs, not which one, so you still need a post-hoc comparison to name the pairs.
  • The classic test assumes every group has the same variance. When variances and group sizes both differ it rejects too often or too rarely, which is why the template offers welch: true.
  • Values must be independent. Repeated measurements of the same subject shrink the within-group spread unfairly and inflate FF.
  • With very large samples a tiny, useless difference becomes significant, so report η2\eta^2 next to the p-value.

Use cases

When to use it

Comparing the mean of one numeric outcome across three or more independent groups, for example a metric under several treatments. With two groups it gives the same answer as the pooled t-test.

In industry

Agriculture
Trial stations compare the mean yield of several crop varieties or fertiliser levels grown on randomised plots, the original use of the method.
Manufacturing
Engineers test whether mean tensile strength differs among three or more suppliers or machine settings.
Marketing
Analysts compare mean order value across several versions of a page or advertisement shown to separate groups of visitors.

Choosing it: what must hold

  • One numeric outcome and one categorical factor with three or more independent groups.
  • Observations that are independent within and across groups.
  • Residuals that are roughly normal within each group.
  • Similar variances across the groups, especially when group sizes are unequal.

When to choose something else

IfUse instead
There are only two groupsA two sample t test, covered under test statistics
Variances are clearly unequalWelch's ANOVA
The data are ordinal or strongly non normalThe Kruskal-Wallis rank test
There is a second factor or a covariateTwo-way ANOVA or ANCOVA

Math foundations

  1. The hypotheses

    H0: μ1=μ2=⋯=μkH1: at least one μi differsH_0:\ \mu_1 = \mu_2 = \cdots = \mu_k \qquad H_1:\ \text{at least one } \mu_i \text{ differs}

    The null hypothesis says all kk population means are the same. The alternative is everything else, which is why a rejection does not point at a specific group.

  2. Splitting the variation

    ∑i=1k∑j=1ni(yij−yˉ)2⏟SST=∑i=1kni(yˉi−yˉ)2⏟SSB+∑i=1k∑j=1ni(yij−yˉi)2⏟SSW\underbrace{\sum_{i=1}^{k}\sum_{j=1}^{n_i}(y_{ij}-\bar{y})^2}_{SS_T} = \underbrace{\sum_{i=1}^{k} n_i(\bar{y}_i-\bar{y})^2}_{SS_B} + \underbrace{\sum_{i=1}^{k}\sum_{j=1}^{n_i}(y_{ij}-\bar{y}_i)^2}_{SS_W}

    The total sum of squares always equals the between part plus the within part. This identity is the whole idea of the method: variation is sorted into explained and unexplained.

  3. Mean squares

    MSB=SSBk−1,MSW=SSWN−kMS_B = \frac{SS_B}{k-1}, \qquad MS_W = \frac{SS_W}{N-k}

    Dividing by degrees of freedom turns each sum into a variance estimate. MSWMS_W estimates the noise variance whatever the means are. MSBMS_B estimates the same variance only when the null hypothesis is true, and something larger otherwise.

  4. The F statistic

    F=MSBMSW∼Fk−1, N−kunder H0F = \frac{MS_B}{MS_W} \sim F_{k-1,\,N-k} \quad \text{under } H_0

    Under the null hypothesis both mean squares estimate one variance, so their ratio is near 1. The p-value is the chance that an Fk−1,N−kF_{k-1,N-k} variable is at least as large as the observed ratio.

  5. Effect size

    η2=SSBSST\eta^2 = \frac{SS_B}{SS_T}

    The share of the total variation that the grouping explains, between 0 and 1. It tells you how big the effect is, which the p-value alone does not.

Symbols

kk
number of groups
nin_i
number of values in group i
NN
total number of values
yijy_{ij}
value j of group i
yˉi\bar{y}_i
mean of group i
yˉ\bar{y}
grand mean of all values
μi\mu_i
population mean of group i
SSB, SSW, SSTSS_B,\ SS_W,\ SS_T
between-group, within-group and total sums of squares
MSB, MSWMS_B,\ MS_W
between-group and within-group mean squares
η2\eta^2
share of the variation explained by the grouping
α\alpha
significance level

Worked by hand

Three groups of three values: (1,2,3)(1,2,3), (2,3,4)(2,3,4) and (6,7,8)(6,7,8). The group means are 2, 3 and 7 and the grand mean is 4.

SSB=3(2−4)2+3(3−4)2+3(7−4)2=12+3+27=42SS_B = 3(2-4)^2 + 3(3-4)^2 + 3(7-4)^2 = 12 + 3 + 27 = 42
SSW=(1+0+1)+(1+0+1)+(1+0+1)=6SS_W = (1+0+1) + (1+0+1) + (1+0+1) = 6
MSB=423−1=21,MSW=69−3=1MS_B = \frac{42}{3-1} = 21, \qquad MS_W = \frac{6}{9-3} = 1
F=211=21,η2=4248=0.875F = \frac{21}{1} = 21, \qquad \eta^2 = \frac{42}{48} = 0.875

F=21F = 21 on (2,6)(2, 6) degrees of freedom is far above the 5% critical value of 5.14, so the null hypothesis is rejected. The grouping explains 87.5% of the variation.

Visual example

Loading the example.

Try this

  • Set the distance between means to 0: F is small, and the split is chance alone.
  • Keep the means fixed and raise the values per group from 3 to 30. The same gaps become significant.
  • Lower α to 0.005 and watch the rejection region retreat to the right.

Code sample

from impl import OneWayAnova
from config import OneWayAnovaConfig

groups = [[6, 8, 4, 5, 3, 4], [8, 12, 9, 11, 6, 8], [13, 9, 11, 8, 7, 12]]
result = OneWayAnova(OneWayAnovaConfig(alpha=0.05)).fit(groups)
print(result["f"], result["p_value"], result["reject"])   # 9.26..., 0.0024..., True
Read the implementation (126 lines)
"""One-way ANOVA: an F test of "all group means are equal".

NumPy and the standard library only. The F distribution's tail probability is computed here from the
regularized incomplete beta function, so the template needs no statistics package.
"""
from __future__ import annotations

import math

import numpy as np

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

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)

class OneWayAnova:
    """Splits the total variation into between-group and within-group parts and compares them."""

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

    def fit(self, groups) -> dict:
        """Run the test.

        groups: a sequence of k >= 2 one-dimensional samples, shapes (n_1,), ..., (n_k,). Sizes may differ,
                each group needs at least 2 values.
        Returns a dict with the ANOVA table (`ss_*`, `df_*`, `ms_*`), `f`, `p_value`, `eta_squared`
        (share of the variation explained by the grouping), `group_means` (k,) and `reject` (p < alpha).
        """
        samples = [np.asarray(g, dtype=float).ravel() for g in groups]
        if len(samples) < 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 = np.array([s.size for s in samples], dtype=float)
        means = np.array([s.mean() for s in samples])
        k, n = len(samples), float(sizes.sum())
        grand = float(np.concatenate(samples).mean())
        ss_between = float(np.sum(sizes * (means - grand) ** 2))
        ss_within = float(sum(np.sum((s - m) ** 2) for s, m in zip(samples, means)))
        df_between, df_within = k - 1.0, n - k
        result = {
            "ss_between": ss_between,
            "ss_within": ss_within,
            "ss_total": ss_between + ss_within,
            "df_between": df_between,
            "df_within": df_within,
            "ms_between": ss_between / df_between,
            "ms_within": ss_within / df_within,
            "eta_squared": ss_between / (ss_between + ss_within) if ss_between + ss_within > 0 else 0.0,
            "group_means": means,
        }
        if self.config.welch:
            f, df1, df2 = self._welch(sizes, means, np.array([s.var(ddof=1) for s in samples]))
        else:
            if ss_within == 0.0:
                f = math.inf if ss_between > 0 else 0.0
            else:
                f = result["ms_between"] / result["ms_within"]
            df1, df2 = df_between, df_within
        result.update(f=f, df1=df1, df2=df2, p_value=f_sf(f, df1, df2) if math.isfinite(f) else 0.0)
        result["reject"] = result["p_value"] < self.config.alpha
        return result

    @staticmethod
    def _welch(sizes: np.ndarray, means: np.ndarray, variances: np.ndarray) -> tuple[float, float, float]:
        """Welch's F and its degrees of freedom. All inputs have shape (k,)."""
        if np.any(variances <= 0):
            raise ValueError("Welch's ANOVA needs a positive variance in every group")
        k = sizes.size
        w = sizes / variances
        w_sum = w.sum()
        mean_w = np.sum(w * means) / w_sum
        lam = np.sum((1.0 - w / w_sum) ** 2 / (sizes - 1.0))
        f = (np.sum(w * (means - mean_w) ** 2) / (k - 1.0)) / (1.0 + 2.0 * (k - 2.0) * lam / (k * k - 1.0))
        return float(f), k - 1.0, float((k * k - 1.0) / (3.0 * lam))
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Create OneWayAnova() and call fit on the three groups from the worked example. Check ss_between, ss_within, f and eta_squared against the hand calculation. Then multiply the third group's spread by 5 around its mean, refit with OneWayAnovaConfig(welch=True) and with the default, and compare f, df2 and p_value.

Check on learning

  1. If you add the same constant to every value in one group, which of SSBSS_B and SSWSS_W changes, and what happens to FF?
    A way to think about it

    A shift moves that group's mean but leaves distances inside the group untouched. Follow each sum of squares through its definition.

  2. Why is running a t-test on every pair of groups a worse plan than one ANOVA when there are six groups?
    A way to think about it

    Count the pairs, then ask how likely at least one false alarm is when each test has a 5% chance of one.

  3. Two studies have identical group means, but in the second every group has four times as many values. How do FF and η2\eta^2 compare between them?
    A way to think about it

    SSBSS_B and SSWSS_W both grow with the sample size, but their degrees of freedom do not grow in the same way. Work out which ratio stays put.

  4. One group has a much larger variance and also the smallest sample. Would you expect classic ANOVA to reject too often or too seldom, and why?
    A way to think about it

    MSWMS_W pools the variances weighted by group size. Ask whether the pooled value understates or overstates the noise in the small, noisy group's mean.