Sign in

Two way

Two-way Analysis of Variance

An analysis of variance with two grouping factors that tests each factor's effect and whether the effect of one depends on the level of the other.

Overview

A one-way ANOVA sorts values by a single label. Often each value carries two labels, such as fertiliser type and watering schedule. Two-way ANOVA lays the data out as a grid, one cell per combination, and splits the variation into four parts: factor A, factor B, their interaction, and noise inside the cells. The interaction is the part of the cell means that the two factors cannot explain by simply adding their separate effects. If it is large, the effect of A is not one number: it changes from one level of B to another. The template handles the balanced case, where every cell holds the same number of values.

A short history

Ronald Fisher extended the analysis of variance to several factors at Rothamsted in the 1920s and argued for factorial experiments, in which every combination of factor levels is tried, in The Design of Experiments in 1935. Frank Yates developed the methods further. Varying one factor at a time cannot reveal whether factors work together. A factorial design tests each factor and their interaction from the same data.

How it works

  1. Arrange the data as an array of shape (a,b,n)(a, b, n): aa levels of A, bb levels of B and nn replicates per cell.
  2. Compute the grand mean, the mean of each level of A, the mean of each level of B and the mean of each cell.
  3. Build SSASS_A and SSBSS_B from how far the level means sit from the grand mean.
  4. Build SSABSS_{AB} from what is left of each cell mean after removing the grand mean and both main effects.
  5. Build the error sum of squares from the spread of values inside each cell.
  6. Divide each sum by its degrees of freedom and form an FF ratio against the error mean square for A, B and A x B.
  7. With interaction: false, or only one value per cell, pool SSABSS_{AB} into the error and test the additive model.

Watch out for

  • When the interaction is significant, the main effects are averages over different behaviours and can mislead, so read the cell means before quoting an effect of A or B.
  • The formulas here assume equal cell sizes. With unbalanced data the sums of squares no longer add up to the total and a regression-based method is needed.
  • With one value per cell there is no within-cell spread, so the interaction cannot be separated from noise and the template refuses to test it.
  • Pooling a real interaction into the error term inflates the error mean square and hides true main effects.

Use cases

When to use it

Designed experiments with two crossed factors and equal cell sizes, when you need to know whether the factors act independently or modify each other.

In industry

Agriculture
A field trial crosses fertiliser type with irrigation level to learn the effect of each and whether a fertiliser works only with enough water.
Manufacturing
Engineers vary temperature and pressure together to find whether the best temperature depends on the pressure used.
Medicine
Factorial trials test two treatments in one study, with patients randomised to each combination, and check whether the treatments interact.

Choosing it: what must hold

  • A numeric outcome and two categorical factors, with observations in every combination of levels.
  • More than one observation per cell if the interaction is to be tested.
  • Independent observations with roughly normal residuals and similar variance across cells.
  • Balanced or nearly balanced cell sizes, or a deliberate choice of sums of squares type when they are unbalanced.

When to choose something else

IfUse instead
Only one factor matters or was variedOne-way ANOVA
The second variable is numeric, not categoricalANCOVA
The same subjects appear in several cellsRepeated measures ANOVA or a mixed effects model
There are several outcomesMANOVA

Math foundations

  1. The model

    yijk=μ+αi+βj+(αβ)ij+εijky_{ijk} = \mu + \alpha_i + \beta_j + (\alpha\beta)_{ij} + \varepsilon_{ijk}

    Each value is a grand mean, plus an effect of its level of A, plus an effect of its level of B, plus an interaction term for that exact cell, plus noise. The three tests ask whether each group of terms is all zero.

  2. Main-effect sums of squares

    SSA=b n∑i=1a(yˉi⋅⋅−yˉ)2,SSB=a n∑j=1b(yˉ⋅j⋅−yˉ)2SS_A = b\,n\sum_{i=1}^{a}(\bar{y}_{i\cdot\cdot}-\bar{y})^2, \qquad SS_B = a\,n\sum_{j=1}^{b}(\bar{y}_{\cdot j\cdot}-\bar{y})^2

    The same between-group idea as one-way ANOVA. Each level mean of A averages b nb\,n values, which is the weight in front.

  3. Interaction sum of squares

    SSAB=n∑i=1a∑j=1b(yˉij⋅−yˉi⋅⋅−yˉ⋅j⋅+yˉ)2SS_{AB} = n\sum_{i=1}^{a}\sum_{j=1}^{b}\left(\bar{y}_{ij\cdot}-\bar{y}_{i\cdot\cdot}-\bar{y}_{\cdot j\cdot}+\bar{y}\right)^2

    Each bracket is a cell mean minus what an additive model would predict for it. If the two factors simply add, every bracket is zero apart from noise.

  4. Error sum of squares

    SSE=∑i=1a∑j=1b∑k=1n(yijk−yˉij⋅)2,SST=SSA+SSB+SSAB+SSESS_E = \sum_{i=1}^{a}\sum_{j=1}^{b}\sum_{k=1}^{n}(y_{ijk}-\bar{y}_{ij\cdot})^2, \qquad SS_T = SS_A + SS_B + SS_{AB} + SS_E

    The spread of replicates around their own cell mean. It measures pure noise, and for balanced data the four parts add up exactly to the total.

  5. The F tests

    FA=SSA/(a−1)MSE,FB=SSB/(b−1)MSE,FAB=SSAB/((a−1)(b−1))MSE,MSE=SSEab(n−1)F_A = \frac{SS_A/(a-1)}{MS_E}, \quad F_B = \frac{SS_B/(b-1)}{MS_E}, \quad F_{AB} = \frac{SS_{AB}/\big((a-1)(b-1)\big)}{MS_E}, \quad MS_E = \frac{SS_E}{ab(n-1)}

    Each effect's mean square is compared with the error mean square. The p-value is the upper tail of the FF distribution with the effect's degrees of freedom and ab(n−1)ab(n-1) error degrees of freedom.

Symbols

a, ba,\ b
number of levels of factor A and of factor B
nn
number of replicates in every cell
yijky_{ijk}
replicate k in the cell at level i of A and level j of B
yˉ\bar{y}
grand mean
yˉi⋅⋅\bar{y}_{i\cdot\cdot}
mean of level i of A
yˉ⋅j⋅\bar{y}_{\cdot j\cdot}
mean of level j of B
yˉij⋅\bar{y}_{ij\cdot}
mean of cell (i, j)
αi, βj\alpha_i,\ \beta_j
main effects of A and B
(αβ)ij(\alpha\beta)_{ij}
interaction effect of cell (i, j)
εijk\varepsilon_{ijk}
random noise
MSEMS_E
error mean square

Worked by hand

A 2 x 2 design with 2 replicates. Cells: A1B1 (1,3)(1,3), A1B2 (3,5)(3,5), A2B1 (5,7)(5,7), A2B2 (11,13)(11,13). Cell means are 2, 4, 6, 12. Means of A are 3 and 9, means of B are 4 and 8, and the grand mean is 6.

SSA=2⋅2[(3−6)2+(9−6)2]=72,SSB=2⋅2[(4−6)2+(8−6)2]=32SS_A = 2\cdot 2\left[(3-6)^2+(9-6)^2\right] = 72, \qquad SS_B = 2\cdot 2\left[(4-6)^2+(8-6)^2\right] = 32
SSAB=2[(2−3−4+6)2+(4−3−8+6)2+(6−9−4+6)2+(12−9−8+6)2]=2⋅4=8SS_{AB} = 2\left[(2-3-4+6)^2+(4-3-8+6)^2+(6-9-4+6)^2+(12-9-8+6)^2\right] = 2\cdot 4 = 8
SSE=4×(1+1)=8,MSE=82⋅2⋅(2−1)=2SS_E = 4\times(1+1) = 8, \qquad MS_E = \frac{8}{2\cdot 2\cdot(2-1)} = 2
FA=72/12=36,FB=32/12=16,FAB=8/12=4F_A = \frac{72/1}{2} = 36, \qquad F_B = \frac{32/1}{2} = 16, \qquad F_{AB} = \frac{8/1}{2} = 4

The parts add to 72+32+8+8=12072+32+8+8=120, the total sum of squares. Against the 5% critical value of 7.71 for (1,4)(1,4) degrees of freedom, A and B are significant and the interaction is not.

Visual example

Loading the example.

Try this

  • Set the interaction to 2 and both effects to 0: the lines cross and neither factor alone shows anything.
  • Set the interaction back to 0 and check that the solid lines are parallel.
  • Raise the noise and watch all three F values shrink while the cell means barely move.

Code sample

import numpy as np
from impl import TwoWayAnova
from config import TwoWayAnovaConfig

y = np.array([[[1, 3], [3, 5]], [[5, 7], [11, 13]]], dtype=float)   # shape (a=2, b=2, n=2)
table = TwoWayAnova(TwoWayAnovaConfig(alpha=0.05)).fit(y)
for source in ("A", "B", "AB"):
    print(source, table[source]["f"], table[source]["p_value"])
Read the implementation (120 lines)
"""Two-way ANOVA for a balanced design: main effects of two factors and their interaction.

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 TwoWayAnovaConfig
except ImportError:  # run from the template's own folder
    from config import TwoWayAnovaConfig

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 TwoWayAnova:
    """Sums of squares, F statistics and p-values for factor A, factor B and A x B."""

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

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

        y: array of shape (a, b, n): a levels of factor A, b levels of factor B, n replicates in every cell.
           A 2-D array (a, b) is read as one value per cell (n = 1), which only supports the additive model.
        Returns a dict keyed by source: "A", "B", "AB" (when tested), "error", "total". Each entry holds
        `ss`, `df`, and for the effects `ms`, `f`, `p_value`, `reject`. "cell_means" holds the (a, b) means.
        """
        y = np.asarray(y, dtype=float)
        if y.ndim == 2:
            y = y[:, :, None]
        if y.ndim != 3:
            raise ValueError(f"y must have shape (a, b, n), got {y.shape}")
        a, b, n = y.shape
        if a < 2 or b < 2:
            raise ValueError("each factor needs at least 2 levels")
        with_interaction = self.config.interaction
        if with_interaction and n < 2:
            raise ValueError("testing the interaction needs at least 2 values per cell; set interaction=false")
        grand = y.mean()
        mean_a = y.mean(axis=(1, 2))  # (a,)
        mean_b = y.mean(axis=(0, 2))  # (b,)
        cell = y.mean(axis=2)  # (a, b)
        ss_a = b * n * float(np.sum((mean_a - grand) ** 2))
        ss_b = a * n * float(np.sum((mean_b - grand) ** 2))
        ss_ab = n * float(np.sum((cell - mean_a[:, None] - mean_b[None, :] + grand) ** 2))
        ss_within = float(np.sum((y - cell[:, :, None]) ** 2))
        ss_total = float(np.sum((y - grand) ** 2))
        df_a, df_b, df_ab, df_within = a - 1, b - 1, (a - 1) * (b - 1), a * b * (n - 1)
        if with_interaction:
            ss_error, df_error = ss_within, df_within
            effects = {"A": (ss_a, df_a), "B": (ss_b, df_b), "AB": (ss_ab, df_ab)}
        else:
            ss_error, df_error = ss_within + ss_ab, df_within + df_ab
            effects = {"A": (ss_a, df_a), "B": (ss_b, df_b)}
        ms_error = ss_error / df_error
        table: dict = {}
        for name, (ss, df) in effects.items():
            ms = ss / df
            if ms_error > 0:
                f = ms / ms_error
            else:
                f = math.inf if ms > 0 else 0.0
            p = f_sf(f, df, df_error) if math.isfinite(f) else 0.0
            table[name] = {"ss": ss, "df": df, "ms": ms, "f": f, "p_value": p, "reject": p < self.config.alpha}
        table["error"] = {"ss": ss_error, "df": df_error, "ms": ms_error}
        table["total"] = {"ss": ss_total, "df": a * b * n - 1}
        table["cell_means"] = cell
        return table
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Build the worked example as a NumPy array of shape (2, 2, 2) and call TwoWayAnova().fit(y). Check the ss and f of "A", "B" and "AB" against the hand calculation. Then refit with TwoWayAnovaConfig(interaction=False) and explain why the f of A and B both changed although the data did not.

Check on learning

  1. In the worked example the A2B2 cell mean is 12, yet an additive model predicts 10. If you replaced it with exactly 10, what would happen to SSABSS_{AB}, and what does that say about what the interaction measures?
    A way to think about it

    Recompute the four brackets of the interaction formula with the new cell mean. Remember that the row, column and grand means change too.

  2. Why can the interaction not be tested when each cell has a single value?
    A way to think about it

    Look at the error degrees of freedom ab(n−1)ab(n-1) when n=1n=1, and ask what would be left to estimate the noise from.

  3. A plot of cell means shows two lines that cross. The test for factor A is not significant. Is it right to say that A has no effect?
    A way to think about it

    A main effect is an average over the levels of B. Think about what averaging does to effects of opposite sign.

  4. Setting interaction: false moves SSABSS_{AB} and its degrees of freedom into the error. When does that make the tests of A and B more powerful, and when less?
    A way to think about it

    The error mean square is a ratio. Compare how much the numerator and the denominator each grow when the true interaction is zero and when it is large.