Skip to content

BCompare groups · anova.repeated

Repeated-measures ANOVA (one within factor)

Do the means differ across conditions measured on the same subjects?

Compares the means of three or more (or two) conditions measured on the same subjects, with Mauchly's sphericity test and Greenhouse–Geisser / Huynh–Feldt corrections, partial and generalized η², and pairwise paired t-tests with a multiple-comparison adjustment. Data in long format: one row per subject and condition.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Rounding”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Repeated-measures ANOVARecorded · Python and R agreeRecorded 2026-11-25 · 37 values compared
R

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

Plots

time by base method per playerHow did each subject change across conditions or time points?
View data
base methodplayertime
Round Outp015.400
Narrow Anglep015.500
Wide Anglep015.550
Round Outp025.850
Narrow Anglep025.700
Wide Anglep025.750
Round Outp035.200
Narrow Anglep035.600
Wide Anglep035.500
Round Outp045.550
Narrow Anglep045.500
Wide Anglep045.400
Round Outp055.900
Narrow Anglep055.850
Wide Anglep055.700
Round Outp065.450
Narrow Anglep065.550
Wide Anglep065.600
Round Outp075.400
Narrow Anglep075.400
Wide Anglep075.350
Round Outp085.450
Narrow Anglep085.500
Wide Anglep085.350
Round Outp095.250
Narrow Anglep095.150
Wide Anglep095
Round Outp105.850
Narrow Anglep105.800
Wide Anglep105.700
Round Outp115.250
Narrow Anglep115.200
Wide Anglep115.100
Round Outp125.650
Narrow Anglep125.550
Wide Anglep125.450
Round Outp135.600
Narrow Anglep135.350
Wide Anglep135.450
Round Outp145.050
Narrow Anglep145
Wide Anglep144.950
Round Outp155.500
Narrow Anglep155.500
Wide Anglep155.400
Round Outp165.450
Narrow Anglep165.550
Wide Anglep165.500
Round Outp175.550
Narrow Anglep175.550
Wide Anglep175.350
Round Outp185.450
Narrow Anglep185.500
Wide Anglep185.550
Round Outp195.500
Narrow Anglep195.450
Wide Anglep195.250
Round Outp205.650
Narrow Anglep205.600
Wide Anglep205.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

SourceSSdfMSFpp (GG)p (HF)
base method0.093720.04696.288.004.008.007
Residual0.3130420.0075————
Subjects4.21921—————

Descriptives

base methodnMeanSDSECI lowCI high
Round Out225.5430.27180.05795.4235.664
Narrow Angle225.5340.25980.05545.4195.649
Wide Angle225.4590.27280.05825.3385.580

Pairwise paired t-tests (Holm adjustment)

ContrastMean differenceSEtdfpp adj.CI lowCI high
Round Out - Narrow Angle0.00910.02620.346421.732.732−0.04550.0637
Round Out - Wide Angle0.08410.03142.67421.014.0280.01870.1495
Narrow Angle - Wide Angle0.07500.01883.98421< .001.0020.03580.1142
  • Within factor base method with 3 levels on 22 subjects; sphericity correction: Huynh–Feldt.
Python

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

SourceSSdfMSFpp (GG)p (HF)
base method0.093720.04696.288.004.008.007
Residual0.3130420.0075————
Subjects4.21921—————

Descriptives

base methodnMeanSDSECI lowCI high
Round Out225.5430.27180.05795.4235.664
Narrow Angle225.5340.25980.05545.4195.649
Wide Angle225.4590.27280.05825.3385.580

Pairwise paired t-tests (Holm adjustment)

ContrastMean differenceSEtdfpp adj.CI lowCI high
Round Out - Narrow Angle0.00910.02620.346421.732.732−0.04550.0637
Round Out - Wide Angle0.08410.03142.67421.014.0280.01870.1495
Narrow Angle - Wide Angle0.07500.01883.98421< .001.0020.03580.1142
  • Within factor base method with 3 levels on 22 subjects; sphericity correction: Huynh–Feldt.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Roundingrounding_times · condition: base method · outcome: time · subject: player
  • Co2 seven levelsco2_long · condition: conc · outcome: uptake · subject: plant
  • Messy longrounding_messy · condition: base method · outcome: time · subject: player
  • Two conditionssleep_long · condition: drug · outcome: extra · subject: patient
  • Degenerate constantrounding_times · condition: base method · outcome: time · subject: player
  • Degenerate single levelrounding_times · condition: base method · outcome: time · subject: player

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Study design: independent / paired / repeated / clustered · Statistics Guide · Step 0 — Prepare your data
  • More than two repeated measures: RM ANOVA, Friedman · Statistics Guide · B — Compare groups
  • Normality (per group, differences or residuals) · Statistics Guide · Step 2 — Check assumptions
  • Sphericity · Statistics Guide · Step 2 — Check assumptions
  • Multiple comparisons · Statistics Guide · Additional considerations
  • Regression (linear, GLM), ANOVA, t-tests, chi-square · DS & ML Decision Guide · Explain — why is it happening?

What you need

Subject IDcategorical · 1 column
Identifies the subject (or block) measured under every condition.
Condition (within)categorical / boolean · 1 column · 2–20 levels
The repeated factor, e.g. time point or treatment.
Outcomenumeric · 1 column
The numeric variable you are analyzing.

Choices you make

assumptions

Sphericity correctiondefault auto

Applied only with three or more conditions; Mauchly's test is shown but does not decide.

  • Automatic (Huynh–Feldt if ε_GG ≥ .75, else Greenhouse–Geisser)(default) — Uses Huynh–Feldt when ε_GG is at least .75 and Greenhouse–Geisser otherwise; the usual choice.
  • Greenhouse–Geisser — Shrinks the degrees of freedom by ε_GG; a little conservative, and safer when sphericity is badly violated.
  • Huynh–Feldt — Shrinks the degrees of freedom by ε_HF; less conservative, and better when sphericity is mildly violated.
  • Lower bound — Uses the smallest possible ε; very conservative, so pick it only as a worst-case check.
  • None (assume sphericity) — Uses the uncorrected F test; pick it only when sphericity is plausible or there are two levels.

posthoc

Pairwise comparisons (paired t)default on

After the overall test, compare each pair of groups, with p-values adjusted for the number of comparisons.

Adjustmentdefault holm

How p-values are corrected for making several comparisons. Holm limits any false alarm; BH limits the share of false discoveries.

  • Holm(default) — Controls the chance of any false positive and always finds at least as much as Bonferroni; a good default.
  • Bonferroni — Multiplies each p by the number of tests; the plainest and strictest control, best for a few comparisons.
  • Benjamini–Hochberg (FDR) — Controls the expected share of false positives among the findings; pick it when screening many comparisons.
  • None — Reports raw p-values; use it for one planned comparison, or say plainly that the results are exploratory.

hypothesis

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Sphericity

    Mauchly's test; the corrections keep the F test valid when it fails.

  • Normality of residuals

    Shapiro–Wilk on the subject × condition residuals.

    • If violated → Friedman test — Ranks within each subject, so it does not assume normal residuals. Changes the question: Compares the conditions' rank distributions, not their means.
  • Complete subjects

    Subjects missing a condition are left out; duplicate cells are averaged.

    • If violated → Linear mixed model (keeps incomplete subjects) — Uses every observed measurement instead of dropping subjects with a missing condition; random intercepts per subject replace the sphericity assumption. Changes the question: Condition effects come from all observed measurements (valid when data are missing at random), not from complete subjects only.

What it reports

  • Tests: Differences among conditions
f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
df1
How much independent information is left to estimate variability after fitting the model.
df2
How much independent information is left to estimate variability after fitting the model.
p
How surprising your data would be if the null hypothesis were true, as a probability.
epsilon
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
df1_corrected
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
df2_corrected
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
p_corrected
How surprising your data would be if the null hypothesis were true, as a probability.
gg_epsilon
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
hf_epsilon
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
lb_epsilon
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
p_gg
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
p_hf
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
mauchly_w
In repeated measures, the assumption that differences between every pair of conditions have equal variance.
mauchly_p
How surprising your data would be if the null hypothesis were true, as a probability.
eta_p
How surprising your data would be if the null hypothesis were true, as a probability.
eta_g
Share of variance explained by an effect, defined so it compares across within- and between-subject designs.
ss_condition
Total squared distance from a mean. ANOVA splits it between sources to show where the variation comes from.
ss_subjects
Total squared distance from a mean. ANOVA splits it between sources to show where the variation comes from.
ss_error
Total squared distance from a mean. ANOVA splits it between sources to show where the variation comes from.
n_subjects
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
sw_p_resid
A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
correction
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
correction_label
Adjust repeated-measures F tests for violated sphericity by multiplying the df by an estimated ε.
n_dropped_subjects
How many independent units the analysis used; it sets precision and power.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.
max_interaction_order
The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.

Per group, level or term: mean[<condition>], diff[<a> - <b>], p_adj[<a> - <b>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Mauchly's p uses the second-order term of Box's (1949) expansion, worked out exactly. stats::mauchly.test behaves as if that term's polynomial ended in + 5 rather than + 2, so for k ≥ 4 its p differs from ours by up to 0.8% (largest at n = k, about 0.3% on CO2). At k = 3 the term is zero and the two agree. W and χ² agree everywhere.
  • Both engines use the same closed-form twin (codesplash.stats.anova.rm_oneway / cs_rm_oneway): Huynh–Feldt in Lecoutre's form (equal to the original with one group).
Python

The exact script CodeSplash ran for example “Rounding” · 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")})],
})
R

The exact script CodeSplash ran for example “Rounding” · 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"))))
))

Sources

  • Mauchly, J. W. (1940). Significance test for sphericity of a normal n-variate distribution. Annals of Mathematical Statistics, 11, 204–209.
  • Greenhouse, S. W., & Geisser, S. (1959). On methods in the analysis of profile data. Psychometrika, 24, 95–112.
  • Huynh, H., & Feldt, L. S. (1976). Estimation of the Box correction for degrees of freedom. Journal of Educational Statistics, 1, 69–82.
  • Lecoutre, B. (1991). A correction for the ε̃ approximate test in repeated measures designs with two or more independent groups. Journal of Educational Statistics, 16, 371–372.
  • Olejnik, S., & Algina, J. (2003). Generalized eta and omega squared statistics. Psychological Methods, 8, 434–447.

From the CodeSplash method registry · anova.repeated v1.1.1.