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
- Arrange the data as an array of shape : levels of A, levels of B and replicates per cell.
- Compute the grand mean, the mean of each level of A, the mean of each level of B and the mean of each cell.
- Build and from how far the level means sit from the grand mean.
- Build from what is left of each cell mean after removing the grand mean and both main effects.
- Build the error sum of squares from the spread of values inside each cell.
- Divide each sum by its degrees of freedom and form an ratio against the error mean square for A, B and A x B.
- With
interaction: false, or only one value per cell, pool 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
| If | Use instead |
|---|---|
| Only one factor matters or was varied | One-way ANOVA |
| The second variable is numeric, not categorical | ANCOVA |
| The same subjects appear in several cells | Repeated measures ANOVA or a mixed effects model |
| There are several outcomes | MANOVA |
Math foundations
The model
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.
Main-effect sums of squares
The same between-group idea as one-way ANOVA. Each level mean of A averages values, which is the weight in front.
Interaction sum of squares
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.
Error sum of squares
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.
The F tests
Each effect's mean square is compared with the error mean square. The p-value is the upper tail of the distribution with the effect's degrees of freedom and error degrees of freedom.
Symbols
- number of levels of factor A and of factor B
- number of replicates in every cell
- replicate k in the cell at level i of A and level j of B
- grand mean
- mean of level i of A
- mean of level j of B
- mean of cell (i, j)
- main effects of A and B
- interaction effect of cell (i, j)
- random noise
- error mean square
Worked by hand
A 2 x 2 design with 2 replicates. Cells: A1B1 , A1B2 , A2B1 , A2B2 . 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.
The parts add to , the total sum of squares. Against the 5% critical value of 7.71 for 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
- 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 , 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.
- 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 when , and ask what would be left to estimate the noise from.
- 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.
- Setting
interaction: falsemoves 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.