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
- Compute each group mean and the grand mean of all values together.
- Add up the between-group sum of squares: each group's squared distance from the grand mean, weighted by its size .
- Add up the within-group sum of squares: every value's squared distance from its own group mean.
- Divide each sum by its degrees of freedom, and , to get the two mean squares.
- Form as the between mean square over the within mean square.
- Read the p-value as the upper tail of the distribution with degrees of freedom and reject the null hypothesis when it is below .
Watch out for
- A significant 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 .
- With very large samples a tiny, useless difference becomes significant, so report 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
| If | Use instead |
|---|---|
| There are only two groups | A two sample t test, covered under test statistics |
| Variances are clearly unequal | Welch's ANOVA |
| The data are ordinal or strongly non normal | The Kruskal-Wallis rank test |
| There is a second factor or a covariate | Two-way ANOVA or ANCOVA |
Math foundations
The hypotheses
The null hypothesis says all population means are the same. The alternative is everything else, which is why a rejection does not point at a specific group.
Splitting the variation
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.
Mean squares
Dividing by degrees of freedom turns each sum into a variance estimate. estimates the noise variance whatever the means are. estimates the same variance only when the null hypothesis is true, and something larger otherwise.
The F statistic
Under the null hypothesis both mean squares estimate one variance, so their ratio is near 1. The p-value is the chance that an variable is at least as large as the observed ratio.
Effect size
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
- number of groups
- number of values in group i
- total number of values
- value j of group i
- mean of group i
- grand mean of all values
- population mean of group i
- between-group, within-group and total sums of squares
- between-group and within-group mean squares
- share of the variation explained by the grouping
- significance level
Worked by hand
Three groups of three values: , and . The group means are 2, 3 and 7 and the grand mean is 4.
on 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..., TrueRead 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
- If you add the same constant to every value in one group, which of and changes, and what happens to ?
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.
- 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.
- Two studies have identical group means, but in the second every group has four times as many values. How do and compare between them?
A way to think about it
and both grow with the sample size, but their degrees of freedom do not grow in the same way. Work out which ratio stays put.
- 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
pools the variances weighted by group size. Ask whether the pooled value understates or overstates the noise in the small, noisy group's mean.