Repeated measures and sphericity
Measuring each subject repeatedly removes differences between subjects, but adds an assumption about how the differences behave. Learn to read Mauchly's test and the corrections.
What runs in CodeSplash
- STAT018Repeated measures ANOVA F tests Runs in CodeSplash
- STAT160Mauchly sphericity test Runs in CodeSplash
- Repeated-measures ANOVA (one within factor) Verified in Python and R
- Mixed (split-plot) ANOVA — one between, one within factor Verified in Python and R
You will be able to
- Explain what sphericity assumes
- Interpret epsilon and the Greenhouse–Geisser and Huynh–Feldt corrections
- Add a between-subjects factor with a mixed ANOVA
From paired to several
ReadA paired t test handles two measurements per person. With more, repeated-measures ANOVA splits away the variation between subjects, so each subject serves as their own control:
With two conditions it is exactly the paired t test: on the sleep study, F = 16.5 and p = .003, and the square root of F is the paired t.
A new assumption
ReadSphericitySphericityIn repeated measures, the assumption that differences between every pair of conditions have equal variance. says the variance of the differences is the same for every pair of conditions.
Measure plants at seven CO2 levels. Neighboring levels are highly correlated and distant ones less so, so the differences between distant levels vary more. Time and dose series often break sphericity for this reason.
See it break
ExploreMake some pairs of conditions correlate more strongly than others. Watch the differences' variances diverge, and watch epsilon fall below 1.
BExplorable · The sphericity explorer
What does sphericity mean for repeated measures, and what does the Greenhouse–Geisser correction fix?
With no true change over time, how often does the uncorrected test reject?
Correlation decays with distance, so far-apart times are less related.
Commit your prediction above to see the result
Make your prediction to see the result.
Predict the correction
PredictPredict first
The CO2 study has 7 levels and 6 numerator degrees of freedom. Sphericity is badly violated, with Greenhouse–Geisser = 0.238.
The correction multiplies the degrees of freedom by . What numerator df does it leave?
Make your guess between 1 and 6 numerator degrees of freedom, then reveal.
Reveal
1.43. The denominator shrinks from 66 to 15.7 too. The uncorrected p-value of 2.39e-24 becomes 2.51e-7: still small, but about seventeen orders of magnitude larger.
Read the result
ReadF(1.65, 34.58) = 6.29, p = .007, η²p = .23
- F
- 6.288
- df (effect)
- 1.647
- df (error)
- 34.582
- p
- .007
- ε applied
- 0.8234
Effect size
- Partial η² 0.2304
- Generalized η² 0.0203
Plots
View data
| base method | player | time |
|---|---|---|
| Round Out | p01 | 5.400 |
| Narrow Angle | p01 | 5.500 |
| Wide Angle | p01 | 5.550 |
| Round Out | p02 | 5.850 |
| Narrow Angle | p02 | 5.700 |
| Wide Angle | p02 | 5.750 |
| Round Out | p03 | 5.200 |
| Narrow Angle | p03 | 5.600 |
| Wide Angle | p03 | 5.500 |
| Round Out | p04 | 5.550 |
| Narrow Angle | p04 | 5.500 |
| Wide Angle | p04 | 5.400 |
| Round Out | p05 | 5.900 |
| Narrow Angle | p05 | 5.850 |
| Wide Angle | p05 | 5.700 |
| Round Out | p06 | 5.450 |
| Narrow Angle | p06 | 5.550 |
| Wide Angle | p06 | 5.600 |
| Round Out | p07 | 5.400 |
| Narrow Angle | p07 | 5.400 |
| Wide Angle | p07 | 5.350 |
| Round Out | p08 | 5.450 |
| Narrow Angle | p08 | 5.500 |
| Wide Angle | p08 | 5.350 |
| Round Out | p09 | 5.250 |
| Narrow Angle | p09 | 5.150 |
| Wide Angle | p09 | 5 |
| Round Out | p10 | 5.850 |
| Narrow Angle | p10 | 5.800 |
| Wide Angle | p10 | 5.700 |
| Round Out | p11 | 5.250 |
| Narrow Angle | p11 | 5.200 |
| Wide Angle | p11 | 5.100 |
| Round Out | p12 | 5.650 |
| Narrow Angle | p12 | 5.550 |
| Wide Angle | p12 | 5.450 |
| Round Out | p13 | 5.600 |
| Narrow Angle | p13 | 5.350 |
| Wide Angle | p13 | 5.450 |
| Round Out | p14 | 5.050 |
| Narrow Angle | p14 | 5 |
| Wide Angle | p14 | 4.950 |
| Round Out | p15 | 5.500 |
| Narrow Angle | p15 | 5.500 |
| Wide Angle | p15 | 5.400 |
| Round Out | p16 | 5.450 |
| Narrow Angle | p16 | 5.550 |
| Wide Angle | p16 | 5.500 |
| Round Out | p17 | 5.550 |
| Narrow Angle | p17 | 5.550 |
| Wide Angle | p17 | 5.350 |
| Round Out | p18 | 5.450 |
| Narrow Angle | p18 | 5.500 |
| Wide Angle | p18 | 5.550 |
| Round Out | p19 | 5.500 |
| Narrow Angle | p19 | 5.450 |
| Wide Angle | p19 | 5.250 |
| Round Out | p20 | 5.650 |
| Narrow Angle | p20 | 5.600 |
| Wide Angle | p20 | 5.400 |
First 60 of 66 rows.
Assumptions
- Normality of residuals — Shapiro–Wilk on the residuals: p = .014 with fewer than 30 subjects; consider the Friedman test.
- Sphericity — Mauchly's W = 0.707, p = .031; ε_GG = 0.774, ε_HF = 0.823. The Huynh–Feldt correction is applied.
- Complete subjects — 22 subjects have a value for every condition.
Within-subjects effects
| Source | SS | df | MS | F | p | p (GG) | p (HF) |
|---|---|---|---|---|---|---|---|
| base method | 0.0937 | 2 | 0.0469 | 6.288 | .004 | .008 | .007 |
| Residual | 0.3130 | 42 | 0.0075 | — | — | — | — |
| Subjects | 4.219 | 21 | — | — | — | — | — |
Descriptives
| base method | n | Mean | SD | SE | CI low | CI high |
|---|---|---|---|---|---|---|
| Round Out | 22 | 5.543 | 0.2718 | 0.0579 | 5.423 | 5.664 |
| Narrow Angle | 22 | 5.534 | 0.2598 | 0.0554 | 5.419 | 5.649 |
| Wide Angle | 22 | 5.459 | 0.2728 | 0.0582 | 5.338 | 5.580 |
Pairwise paired t-tests (Holm adjustment)
| Contrast | Mean difference | SE | t | df | p | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|---|
| Round Out - Narrow Angle | 0.0091 | 0.0262 | 0.3464 | 21 | .732 | .732 | −0.0455 | 0.0637 |
| Round Out - Wide Angle | 0.0841 | 0.0314 | 2.674 | 21 | .014 | .028 | 0.0187 | 0.1495 |
| Narrow Angle - Wide Angle | 0.0750 | 0.0188 | 3.984 | 21 | < .001 | .002 | 0.0358 | 0.1142 |
- Within factor base method with 3 levels on 22 subjects; sphericity correction: Huynh–Feldt.
The exact R script · R R version 4.5.1 (2025-06-13)
# Repeated-measures ANOVA (one within factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.repeated 1.1.1 · spec 4938b4bf2bc976f7
# Dataset: rounding_times (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rounding_times.parquet", col_select = c("player", "base method", "time")))
n_input <- nrow(df)
df[["player"]] <- factor(df[["player"]], levels = c("p01", "p02", "p03", "p04", "p05", "p06", "p07", "p08", "p09", "p10", "p11", "p12", "p13", "p14", "p15", "p16", "p17", "p18", "p19", "p20", "p21", "p22")) # stored level order
df[["base method"]] <- factor(df[["base method"]], levels = c("Round Out", "Narrow Angle", "Wide Angle")) # stored level order
df <- df[stats::complete.cases(df[c("player", "base method", "time")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("player", "base method", "time")) # infinite values stop the run (registry/errors.yaml)
# %% Wide format: one row per subject, one column per condition
subj <- "player"
cond <- "base method"
y <- "time"
cells <- table(df[[subj]], df[[cond]])
n_dup <- sum(cells > 1)
agg <- stats::aggregate(df[[y]], by = list(s = df[[subj]], c = df[[cond]]), FUN = mean)
wide <- matrix(NA_real_, nlevels(df[[subj]]), nlevels(df[[cond]]), dimnames = list(levels(df[[subj]]), levels(df[[cond]])))
wide[cbind(as.character(agg$s), as.character(agg$c))] <- agg$x
complete <- wide[stats::complete.cases(wide), , drop = FALSE]
n_dropped_subjects <- sum(rowSums(!is.na(wide)) > 0) - nrow(complete)
if (n_dup > 0) warnings <- c(warnings, sprintf("%d subject × condition cell(s) had more than one value; their mean was used.", n_dup))
if (n_dropped_subjects > 0) warnings <- c(warnings, sprintf("%d subject(s) without a value for every condition were left out.", n_dropped_subjects))
conditions <- colnames(complete)
subjects <- rownames(complete)
Y <- unname(complete)
n_subj <- nrow(Y)
k <- ncol(Y)
if (n_subj < 2) {
cs_error("CS_E_UNDEFINED", what = "This repeated-measures analysis", reason = "fewer than two subjects have a value for every condition")
}
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = cond, min = 2, k = k)
if (length(unique(as.vector(Y))) < 2) cs_error("CS_E_CONSTANT", column = y) # a constant outcome leaves nothing to test (the F ratios would be 0/0)
# %% Test
correction <- "auto" # auto: Huynh-Feldt if eps_GG >= .75, else Greenhouse-Geisser
conf <- 0.95
# No error variation (every subject changes by the same amount between conditions): the F ratio is undefined.
resid0 <- sweep(sweep(Y, 1, rowMeans(Y)), 2, colMeans(Y)) + mean(Y)
if (sum(resid0^2) <= 1e-12 * sum((Y - mean(Y))^2)) {
cs_error("CS_E_UNDEFINED", what = "Repeated-measures ANOVA",
reason = "every subject changes by the same amount between conditions, so there is no error variation to test against")
}
r <- cs_rm_oneway(Y) # sums of squares, Mauchly, epsilon (twin of codesplash.stats.anova.rm_oneway)
applied <- if (k < 3 || correction == "none") "none" else if (correction == "auto") (if (r$gg >= 0.75) "hf" else "gg") else correction
epsilon <- switch(applied, none = 1, gg = r$gg, hf = r$hf, lb = r$lb)
df1c <- r$df1 * epsilon
df2c <- r$df2 * epsilon
p_corrected <- pf(r$f, df1c, df2c, lower.tail = FALSE)
p_gg <- pf(r$f, r$df1 * r$gg, r$df2 * r$gg, lower.tail = FALSE)
p_hf <- pf(r$f, r$df1 * r$hf, r$df2 * r$hf, lower.tail = FALSE)
labels <- c(none = "none", gg = "Greenhouse–Geisser", hf = "Huynh–Feldt", lb = "lower-bound")
# %% Pairwise comparisons: paired t on each pair of conditions
pairs <- data.frame()
if (TRUE && k >= 2) {
for (i in seq_len(k - 1)) {
for (j in (i + 1):k) {
d <- Y[, i] - Y[, j]
se <- sd(d) / sqrt(n_subj)
t <- mean(d) / se
q <- qt(0.5 + conf / 2, n_subj - 1)
pairs <- rbind(pairs, data.frame(contrast = paste(conditions[i], "-", conditions[j]), estimate = mean(d), se = se, t = t,
df = n_subj - 1, p = 2 * pt(abs(t), n_subj - 1, lower.tail = FALSE),
ci_low = mean(d) - q * se, ci_high = mean(d) + q * se, stringsAsFactors = FALSE))
}
}
pairs$p_adj <- cs_p_adjust(pairs$p, "holm")
}
# %% Assumptions
assumptions <- list()
resid <- Y - outer(rowMeans(Y), rep(1, k)) - outer(rep(1, n_subj), colMeans(Y)) + mean(Y)
sw_p <- if (length(resid) >= 3 && length(resid) <= 5000) shapiro.test(as.vector(t(resid)))$p.value else NULL
if (is.null(sw_p)) {
assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = "info", detail = "Too few (or too many) residuals for Shapiro–Wilk.")
} else if (sw_p < 0.05 && n_subj < 30) {
assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = "warn", p = sw_p,
detail = sprintf("Shapiro–Wilk on the residuals: %s with fewer than 30 subjects; consider the Friedman test.", cs_fmt_p(sw_p)))
} else {
assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = if (sw_p >= 0.05) "pass" else "info", p = sw_p,
detail = paste0(sprintf("Shapiro–Wilk on the residuals: %s", cs_fmt_p(sw_p)),
if (sw_p >= 0.05) "." else "; with 30 or more subjects the F test is robust."))
}
if (k < 3) {
assumptions[[2]] <- list(key = "sphericity", label = "Sphericity", status = "pass", detail = "Always satisfied with two conditions.")
} else if (is.nan(r$mauchly_p)) {
assumptions[[2]] <- list(key = "sphericity", label = "Sphericity", status = "info",
detail = sprintf("Mauchly's test needs more subjects than conditions; ε_GG = %.3f.", r$gg))
} else {
bad <- r$mauchly_p < 0.05
assumptions[[2]] <- list(key = "sphericity", label = "Sphericity", status = if (bad) "warn" else "pass",
statistic = r$mauchly_w, p = r$mauchly_p,
detail = paste0(sprintf("Mauchly's W = %.3f, %s; ε_GG = %.3f, ε_HF = %.3f.", r$mauchly_w, cs_fmt_p(r$mauchly_p), r$gg, r$hf),
if (applied != "none") sprintf(" The %s correction is applied.", labels[[applied]])
else if (bad) " No correction is applied." else ""))
}
assumptions[[3]] <- list(key = "complete", label = "Complete subjects", status = if (n_dropped_subjects > 0) "warn" else "pass",
detail = paste0(sprintf("%d subjects have a value for every condition", n_subj),
if (n_dropped_subjects > 0) sprintf("; %d were left out.", n_dropped_subjects) else "."))
# %% Result
q <- qt(0.5 + conf / 2, n_subj - 1)
descriptives <- data.frame(condition = conditions, n = n_subj, mean = colMeans(Y), sd = apply(Y, 2, sd),
se = apply(Y, 2, sd) / sqrt(n_subj), stringsAsFactors = FALSE)
descriptives$ci_low <- descriptives$mean - q * descriptives$se
descriptives$ci_high <- descriptives$mean + q * descriptives$se
values <- list(
f = r$f, df1 = r$df1, df2 = r$df2, p = r$p, epsilon = epsilon, df1_corrected = df1c, df2_corrected = df2c,
p_corrected = p_corrected, gg_epsilon = r$gg, hf_epsilon = r$hf, lb_epsilon = r$lb, p_gg = p_gg, p_hf = p_hf,
mauchly_w = r$mauchly_w, mauchly_p = r$mauchly_p, eta_p = r$eta_p, eta_g = r$eta_g,
ss_condition = r$ss_cond, ss_subjects = r$ss_subj, ss_error = r$ss_err, n_subjects = n_subj, k = k,
sw_p_resid = sw_p, correction = applied, correction_label = labels[[applied]], n_dropped_subjects = n_dropped_subjects
)
for (j in seq_len(k)) values[[sprintf("mean[%s]", conditions[j])]] <- descriptives$mean[j]
for (r_ in seq_len(nrow(pairs))) {
values[[sprintf("diff[%s]", pairs$contrast[r_])]] <- pairs$estimate[r_]
values[[sprintf("p_adj[%s]", pairs$contrast[r_])]] <- pairs$p_adj[r_]
}
tables <- list(
list(key = "anova", title = "Within-subjects effects",
columns = list(list(key = "source", label = "Source", type = "string"), list(key = "ss", label = "SS", type = "number"),
list(key = "df", label = "df", type = "number"), list(key = "ms", label = "MS", type = "number"),
list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "p_gg", label = "p (GG)", type = "pvalue"), list(key = "p_hf", label = "p (HF)", type = "pvalue")),
rows = list(list(source = cond, ss = r$ss_cond, df = r$df1, ms = r$ss_cond / r$df1, f = r$f, p = r$p, p_gg = p_gg, p_hf = p_hf),
list(source = "Residual", ss = r$ss_err, df = r$df2, ms = r$ss_err / r$df2),
list(source = "Subjects", ss = r$ss_subj, df = n_subj - 1))),
list(key = "descriptives", title = "Descriptives",
columns = list(list(key = "condition", label = cond, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "ci_low", label = "CI low", type = "number"),
list(key = "ci_high", label = "CI high", type = "number")),
rows = descriptives)
)
if (nrow(pairs) > 0) {
adjust_label <- c(holm = "Holm", bonferroni = "Bonferroni", BH = "Benjamini–Hochberg", none = "no")[["holm"]]
tables[[3]] <- list(key = "posthoc", title = sprintf("Pairwise paired t-tests (%s adjustment)", adjust_label),
columns = list(list(key = "contrast", label = "Contrast", type = "string"), list(key = "estimate", label = "Mean difference", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue"),
list(key = "p_adj", label = "p adj.", type = "pvalue"), list(key = "ci_low", label = "CI low", type = "number"),
list(key = "ci_high", label = "CI high", type = "number")),
rows = pairs)
}
long_s <- rep(subjects, each = k)
long_c <- rep(conditions, times = n_subj)
long_v <- as.vector(t(Y))
keep <- seq_len(min(length(long_v), 5000))
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
values$max_interaction_order <- 1
eps_text <- if (applied != "none") sprintf(", %s ε = %.3f", labels[[applied]], epsilon) else ""
cs_publish(list(
method = "anova.repeated",
methodVersion = "1.1.1",
title = "Repeated-measures ANOVA",
engine = cs_engine_info("stats", "nanoparquet"),
n = n_subj,
summary = sprintf("F(%s, %s) = %s, %s%s; partial η² = %.3f.", cs_fmt_num(df1c), cs_fmt_num(df2c), cs_fmt_num(r$f), cs_fmt_p(p_corrected), eps_text, r$eta_p),
apa = sprintf("F(%s, %s) = %s, %s, η²p = %s", cs_fmt_num(df1c), cs_fmt_num(df2c), cs_fmt_num(r$f), cs_fmt_p(p_corrected), cs_fmt_num(r$eta_p, 2, leading_zero = FALSE)),
statistics = list(
list(key = "f", label = "F", value = r$f), list(key = "df1_corrected", label = "df (effect)", value = df1c),
list(key = "df2_corrected", label = "df (error)", value = df2c), list(key = "p_corrected", label = "p", value = p_corrected, format = "p"),
list(key = "epsilon", label = "ε applied", value = epsilon)
),
tables = tables,
effectSizes = list(
list(key = "eta_p", label = "Partial η²", value = r$eta_p, method = "SS_condition / (SS_condition + SS_error)"),
list(key = "eta_g", label = "Generalized η²", value = r$eta_g, method = "Olejnik & Algina (2003)")
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Within factor %s with %d levels on %d subjects; sphericity correction: %s.", cond, k, n_subj, labels[[applied]])),
values = values,
charts = list(cs_chart("profiles", "paired-lines", sprintf("%s by %s per %s", y, cond, subj), list(
subject = cs_col(subj, long_s[keep], "categorical"),
condition = cs_col(cond, long_c[keep], "categorical", levels = conditions),
value = cs_col(y, long_v[keep], "numeric"))))
))
F(1.65, 34.58) = 6.29, p = .007, η²p = .23
- F
- 6.288
- df (effect)
- 1.647
- df (error)
- 34.582
- p
- .007
- ε applied
- 0.8234
Effect size
- Partial η² 0.2304
- Generalized η² 0.0203
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of residuals — Shapiro–Wilk on the residuals: p = .014 with fewer than 30 subjects; consider the Friedman test.
- Sphericity — Mauchly's W = 0.707, p = .031; ε_GG = 0.774, ε_HF = 0.823. The Huynh–Feldt correction is applied.
- Complete subjects — 22 subjects have a value for every condition.
Within-subjects effects
| Source | SS | df | MS | F | p | p (GG) | p (HF) |
|---|---|---|---|---|---|---|---|
| base method | 0.0937 | 2 | 0.0469 | 6.288 | .004 | .008 | .007 |
| Residual | 0.3130 | 42 | 0.0075 | — | — | — | — |
| Subjects | 4.219 | 21 | — | — | — | — | — |
Descriptives
| base method | n | Mean | SD | SE | CI low | CI high |
|---|---|---|---|---|---|---|
| Round Out | 22 | 5.543 | 0.2718 | 0.0579 | 5.423 | 5.664 |
| Narrow Angle | 22 | 5.534 | 0.2598 | 0.0554 | 5.419 | 5.649 |
| Wide Angle | 22 | 5.459 | 0.2728 | 0.0582 | 5.338 | 5.580 |
Pairwise paired t-tests (Holm adjustment)
| Contrast | Mean difference | SE | t | df | p | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|---|
| Round Out - Narrow Angle | 0.0091 | 0.0262 | 0.3464 | 21 | .732 | .732 | −0.0455 | 0.0637 |
| Round Out - Wide Angle | 0.0841 | 0.0314 | 2.674 | 21 | .014 | .028 | 0.0187 | 0.1495 |
| Narrow Angle - Wide Angle | 0.0750 | 0.0188 | 3.984 | 21 | < .001 | .002 | 0.0358 | 0.1142 |
- Within factor base method with 3 levels on 22 subjects; sphericity correction: Huynh–Feldt.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Repeated-measures ANOVA (one within factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.repeated 1.1.1 · spec 4938b4bf2bc976f7
# Dataset: rounding_times (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import anova as csa
from codesplash.stats.padjust import p_adjust
# %% Data
df = pd.read_parquet("tests/parity/fixtures/rounding_times.parquet", columns=["player", "base method", "time"])
n_input = len(df)
df["player"] = pd.Categorical(df["player"], categories=["p01", "p02", "p03", "p04", "p05", "p06", "p07", "p08", "p09", "p10", "p11", "p12", "p13", "p14", "p15", "p16", "p17", "p18", "p19", "p20", "p21", "p22"]) # stored level order
df["base method"] = pd.Categorical(df["base method"], categories=["Round Out", "Narrow Angle", "Wide Angle"]) # stored level order
df = df.dropna(subset=["player", "base method", "time"]) # listwise deletion over the analysis columns
df["player"] = df["player"].cat.remove_unused_categories()
df["base method"] = df["base method"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["player", "base method", "time"]) # infinite values stop the run (registry/errors.yaml)
# %% Wide format: one row per subject, one column per condition
subj, cond, y = "player", "base method", "time"
cells = df.groupby([subj, cond], observed=True)[y].size()
n_dup = int((cells > 1).sum())
wide = df.pivot_table(index=subj, columns=cond, values=y, aggfunc="mean", observed=False)
wide = wide.reindex(index=df[subj].cat.categories, columns=df[cond].cat.categories)
complete = wide.dropna()
n_dropped_subjects = int(wide.notna().any(axis=1).sum() - len(complete))
if n_dup:
warnings.append(f"{n_dup} subject × condition cell(s) had more than one value; their mean was used.")
if n_dropped_subjects:
warnings.append(f"{n_dropped_subjects} subject(s) without a value for every condition were left out.")
conditions = [str(c) for c in complete.columns]
subjects = [str(s) for s in complete.index]
Y = complete.to_numpy(dtype=float)
n_subj, k = Y.shape
if n_subj < 2:
cs.cs_error("CS_E_UNDEFINED", what="This repeated-measures analysis", reason="fewer than two subjects have a value for every condition")
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=cond, min=2, k=k)
if len(np.unique(Y)) < 2: # a constant outcome leaves nothing to test (the F ratios would be 0/0)
cs.cs_error("CS_E_CONSTANT", column=y)
# %% Test
correction = "auto" # auto: Huynh–Feldt if ε_GG ≥ .75, else Greenhouse–Geisser
conf = 0.95
# No error variation (every subject changes by the same amount between conditions): the F ratio is undefined.
resid0 = Y - Y.mean(axis=1, keepdims=True) - Y.mean(axis=0, keepdims=True) + Y.mean()
if float((resid0**2).sum()) <= 1e-12 * float(((Y - Y.mean()) ** 2).sum()):
cs.cs_error("CS_E_UNDEFINED", what="Repeated-measures ANOVA",
reason="every subject changes by the same amount between conditions, so there is no error variation to test against")
r = csa.rm_oneway(Y) # sums of squares, Mauchly, ε (twin of R's cs_rm_oneway)
if k < 3 or correction == "none":
applied = "none"
elif correction == "auto":
applied = "hf" if r["gg"] >= 0.75 else "gg"
else:
applied = correction
epsilon = {"none": 1.0, "gg": r["gg"], "hf": r["hf"], "lb": r["lb"]}[applied]
df1c, df2c = r["df1"] * epsilon, r["df2"] * epsilon
p_corrected = float(stats.f.sf(r["f"], df1c, df2c))
p_gg = float(stats.f.sf(r["f"], r["df1"] * r["gg"], r["df2"] * r["gg"]))
p_hf = float(stats.f.sf(r["f"], r["df1"] * r["hf"], r["df2"] * r["hf"]))
labels = {"none": "none", "gg": "Greenhouse–Geisser", "hf": "Huynh–Feldt", "lb": "lower-bound"}
# %% Pairwise comparisons: paired t on each pair of conditions
pairs = []
if True and k >= 2:
for i in range(k):
for j in range(i + 1, k):
d = Y[:, i] - Y[:, j]
se = d.std(ddof=1) / np.sqrt(n_subj)
t = d.mean() / se
q = stats.t.ppf(0.5 + conf / 2, n_subj - 1)
pairs.append({"contrast": f"{conditions[i]} - {conditions[j]}", "estimate": float(d.mean()), "se": float(se),
"t": float(t), "df": n_subj - 1, "p": float(2 * stats.t.sf(abs(t), n_subj - 1)),
"ci_low": float(d.mean() - q * se), "ci_high": float(d.mean() + q * se)})
for row, pa in zip(pairs, p_adjust([x["p"] for x in pairs], "holm")):
row["p_adj"] = float(pa)
# %% Assumptions
assumptions = []
resid = Y - Y.mean(axis=1, keepdims=True) - Y.mean(axis=0, keepdims=True) + Y.mean()
sw_p = float(stats.shapiro(resid.ravel()).pvalue) if 3 <= resid.size <= 5000 else None
if sw_p is None:
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "info", "detail": "Too few (or too many) residuals for Shapiro–Wilk."})
elif sw_p < 0.05 and n_subj < 30:
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "warn", "p": sw_p,
"detail": f"Shapiro–Wilk on the residuals: {cs.fmt_p(sw_p)} with fewer than 30 subjects; consider the Friedman test."})
else:
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "pass" if sw_p >= 0.05 else "info", "p": sw_p,
"detail": f"Shapiro–Wilk on the residuals: {cs.fmt_p(sw_p)}" + ("." if sw_p >= 0.05 else "; with 30 or more subjects the F test is robust.")})
if k < 3:
assumptions.append({"key": "sphericity", "label": "Sphericity", "status": "pass", "detail": "Always satisfied with two conditions."})
elif np.isnan(r["mauchly_p"]):
assumptions.append({"key": "sphericity", "label": "Sphericity", "status": "info",
"detail": f"Mauchly's test needs more subjects than conditions; ε_GG = {r['gg']:.3f}."})
else:
bad = r["mauchly_p"] < 0.05
assumptions.append({"key": "sphericity", "label": "Sphericity", "status": "warn" if bad else "pass",
"statistic": r["mauchly_w"], "p": r["mauchly_p"],
"detail": f"Mauchly's W = {r['mauchly_w']:.3f}, {cs.fmt_p(r['mauchly_p'])}; ε_GG = {r['gg']:.3f}, ε_HF = {r['hf']:.3f}."
+ (f" The {labels[applied]} correction is applied." if applied != "none" else (" No correction is applied." if bad else ""))})
assumptions.append({"key": "complete", "label": "Complete subjects", "status": "warn" if n_dropped_subjects else "pass",
"detail": f"{n_subj} subjects have a value for every condition" + (f"; {n_dropped_subjects} were left out." if n_dropped_subjects else ".")})
# %% Result
descriptives = []
for j, c in enumerate(conditions):
x = Y[:, j]
se = x.std(ddof=1) / np.sqrt(n_subj)
q = stats.t.ppf(0.5 + conf / 2, n_subj - 1)
descriptives.append({"condition": c, "n": n_subj, "mean": float(x.mean()), "sd": float(x.std(ddof=1)), "se": float(se),
"ci_low": float(x.mean() - q * se), "ci_high": float(x.mean() + q * se)})
values = {
"f": r["f"], "df1": r["df1"], "df2": r["df2"], "p": r["p"], "epsilon": epsilon, "df1_corrected": df1c, "df2_corrected": df2c,
"p_corrected": p_corrected, "gg_epsilon": r["gg"], "hf_epsilon": r["hf"], "lb_epsilon": r["lb"], "p_gg": p_gg, "p_hf": p_hf,
"mauchly_w": r["mauchly_w"], "mauchly_p": r["mauchly_p"], "eta_p": r["eta_p"], "eta_g": r["eta_g"],
"ss_condition": r["ss_cond"], "ss_subjects": r["ss_subj"], "ss_error": r["ss_err"], "n_subjects": n_subj, "k": k,
"sw_p_resid": sw_p, "correction": applied, "correction_label": labels[applied], "n_dropped_subjects": n_dropped_subjects,
}
for row in descriptives:
values[f"mean[{row['condition']}]"] = row["mean"]
for row in pairs:
values[f"diff[{row['contrast']}]"] = row["estimate"]
values[f"p_adj[{row['contrast']}]"] = row["p_adj"]
long_rows = [(s, c, Y[i, j]) for i, s in enumerate(subjects) for j, c in enumerate(conditions)][:5000]
tables = [
{"key": "anova", "title": "Within-subjects effects", "columns": [
{"key": "source", "label": "Source", "type": "string"}, {"key": "ss", "label": "SS", "type": "number"},
{"key": "df", "label": "df", "type": "number"}, {"key": "ms", "label": "MS", "type": "number"},
{"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "p_gg", "label": "p (GG)", "type": "pvalue"}, {"key": "p_hf", "label": "p (HF)", "type": "pvalue"}],
"rows": [
{"source": cond, "ss": r["ss_cond"], "df": r["df1"], "ms": r["ss_cond"] / r["df1"], "f": r["f"], "p": r["p"], "p_gg": p_gg, "p_hf": p_hf},
{"source": "Residual", "ss": r["ss_err"], "df": r["df2"], "ms": r["ss_err"] / r["df2"]},
{"source": "Subjects", "ss": r["ss_subj"], "df": n_subj - 1}]},
{"key": "descriptives", "title": "Descriptives", "columns": [
{"key": "condition", "label": cond, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "ci_low", "label": "CI low", "type": "number"},
{"key": "ci_high", "label": "CI high", "type": "number"}], "rows": descriptives},
]
if pairs:
adjust_label = {"holm": "Holm", "bonferroni": "Bonferroni", "BH": "Benjamini–Hochberg", "none": "no"}["holm"]
tables.append({"key": "posthoc", "title": f"Pairwise paired t-tests ({adjust_label} adjustment)",
"columns": [{"key": "contrast", "label": "Contrast", "type": "string"}, {"key": "estimate", "label": "Mean difference", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "p_adj", "label": "p adj.", "type": "pvalue"}, {"key": "ci_low", "label": "CI low", "type": "number"},
{"key": "ci_high", "label": "CI high", "type": "number"}], "rows": pairs})
eps_text = f", {labels[applied]} ε = {epsilon:.3f}" if applied != "none" else ""
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
values["max_interaction_order"] = 1
cs.publish({
"method": "anova.repeated",
"methodVersion": "1.1.1",
"title": "Repeated-measures ANOVA",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n_subj,
"summary": f"F({cs.fmt_num(df1c)}, {cs.fmt_num(df2c)}) = {cs.fmt_num(r['f'])}, {cs.fmt_p(p_corrected)}{eps_text}; partial η² = {r['eta_p']:.3f}.",
"apa": f"F({cs.fmt_num(df1c)}, {cs.fmt_num(df2c)}) = {cs.fmt_num(r['f'])}, {cs.fmt_p(p_corrected)}, η²p = {cs.fmt_num(r['eta_p'], 2, leading_zero=False)}",
"statistics": [
{"key": "f", "label": "F", "value": r["f"]}, {"key": "df1_corrected", "label": "df (effect)", "value": df1c},
{"key": "df2_corrected", "label": "df (error)", "value": df2c}, {"key": "p_corrected", "label": "p", "value": p_corrected, "format": "p"},
{"key": "epsilon", "label": "ε applied", "value": epsilon},
],
"tables": tables,
"effectSizes": [
{"key": "eta_p", "label": "Partial η²", "value": r["eta_p"], "method": "SS_condition / (SS_condition + SS_error)"},
{"key": "eta_g", "label": "Generalized η²", "value": r["eta_g"], "method": "Olejnik & Algina (2003)"},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Within factor {cond} with {k} levels on {n_subj} subjects; sphericity correction: {labels[applied]}."],
"values": values,
"charts": [cs.chart("profiles", "paired-lines", f"{y} by {cond} per {subj}", {
"subject": cs.col(subj, [x[0] for x in long_rows], "categorical"),
"condition": cs.col(cond, [x[1] for x in long_rows], "categorical", levels=conditions),
"value": cs.col(y, [float(x[2]) for x in long_rows], "numeric")})],
})
Twenty-two players ran bases three ways. Mauchly's test gives W = 0.71, p = .031. With = 0.77, above the usual cutoff of , CodeSplash applies Huynh–Feldt ( = 0.82): F = 6.29 on corrected df, p = .007, generalized = 0.020.
Add groups
ReadA mixed ANOVA adds a between-subjects factor. Here the plants were either chilled or not, and each was measured at seven CO2 levels. Three effects:
- CO2, within plants: F = 60.3, p < .001
- Treatment, between plants: F = 2.55, p = .141
- Their interaction: F = 1.50, p = .252
With only 12 plants, the between-plant test has little power.
Check your understanding
CheckpointCheck yourself
A design has 5 conditions. What is the smallest value epsilon can take (the lower bound, 1 / (k − 1))?
Show the answer
Answer: 0.25
1 / (5 − 1) = 0.25. Using it gives the most conservative correction.
Check yourself
Your repeated-measures design has only two conditions. What about sphericity?
Show the answer
Answer: a
With two conditions there is one difference variance, so nothing can be unequal. CodeSplash reports ε = 1.
Check yourself
Mauchly's test gives p = 0.40 with 8 subjects. What should you do?
Show the answer
Answer: b
A non-significant Mauchly test with few subjects says little. The correction costs almost nothing when sphericity holds.
Check yourself
Plants get one of two treatments, and each plant is measured at seven CO2 levels. Which design is this?
Show the answer
Answer: a
Each plant sits in one treatment but sees every CO2 level. A two-way between-subjects analysis would treat its seven measurements as independent.
Check yourself
In a mixed ANOVA, which term asks whether the treatment groups changed differently across conditions?
Show the answer
Answer: c
The between effect averages over conditions, and the within effect averages over groups. Only the interaction compares how the groups' patterns differ.
Check yourself
Which terms in a mixed ANOVA need a sphericity correction?
Show the answer
Answer: a
Sphericity concerns differences between repeated conditions. The between-subjects effect uses one average per subject, so it doesn't involve them.
Do it in CodeSplash
In the appUse long data, one row per measurement. Fill Subject ID, Condition (within) and Outcome. Sphericity correction defaults to Automatic: Huynh–Feldt when , otherwise Greenhouse–Geisser. Mixed ANOVA adds a between-subjects Groups role.
# pip install pingouin
import pandas as pd
import pingouin as pg
df = pd.read_csv("rounding_times.csv") # long: one row per measurement
print(pg.rm_anova(df, dv="time", within="base method", subject="player", correction=True))# install.packages("afex")
df <- read.csv("rounding_times.csv") # long: one row per measurement
afex::aov_ez("player", "time", df, within = "base.method")Recap
Recap- Repeated-measures ANOVA removes differences between subjects, and generalizes the paired t test.
- Sphericity asks for equal variances of all the pairwise differences.
- Always correct with . Add a between factor with mixed ANOVA, and expect that factor to have less power.
Concepts in this lesson