BCompare groups · anova.mixed
Mixed (split-plot) ANOVA — one between, one within factor
Do groups differ, do conditions differ, and do the groups change differently across conditions?
Split-plot ANOVA for a between-subjects factor (e.g. treatment group) crossed with a within-subjects factor (e.g. time): between, within and interaction effects with Type III sums of squares for unequal group sizes, Mauchly's test and Greenhouse–Geisser / Huynh–Feldt (Lecoutre) corrections for the within effects, partial and generalized η². Data in long format.
A real result
Example “Co2 type”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
interaction: F(1.89, 18.89) = 9.32, p = .002
- p (interaction)
- .002
- ε applied
- 0.3148
Effect size
- Partial η² (interaction) 0.4825
- Generalized η² (interaction) 0.1648
Plots
View data
| CI high | CI low | Mean uptake | type | conc |
|---|---|---|---|---|
| 16.735 | 11.399 | 14.067 | Quebec | 95 |
| 31.417 | 22.750 | 27.083 | Quebec | 175 |
| 39.539 | 32.328 | 35.933 | Quebec | 250 |
| 41.720 | 34.447 | 38.083 | Quebec | 350 |
| 42.042 | 34.224 | 38.133 | Quebec | 500 |
| 42.609 | 36.391 | 39.500 | Quebec | 675 |
| 44.746 | 39.254 | 42 | Quebec | 1000 |
| 11.988 | 8.912 | 10.450 | Mississippi | 95 |
| 21.437 | 13.530 | 17.483 | Mississippi | 175 |
| 28.964 | 14.669 | 21.817 | Mississippi | 250 |
| 31.282 | 15.218 | 23.250 | Mississippi | 350 |
| 32.107 | 15.127 | 23.617 | Mississippi | 500 |
| 32.143 | 16.657 | 24.400 | Mississippi | 675 |
| 33.405 | 16.928 | 25.167 | Mississippi | 1000 |
Assumptions
- Sphericity — Mauchly's W = 0.000, p < .001; ε_GG = 0.315, ε_HF = 0.386. The Greenhouse–Geisser correction is applied.
- Equal variances between groups — Brown–Forsythe on the subject means: F = 7.57, p = .020.
- Normality of residuals — Shapiro–Wilk on the within-subject residuals: p = .847.
- Complete subjects — 12 subjects have a value for every condition.
Mixed ANOVA (Type III; within-subject df corrected)
| Source | SS | df | F | p | η²p | η²G |
|---|---|---|---|---|---|---|
| type | 3365.53 | 1 | 22.487 | < .001 | 0.6922 | 0.6394 |
| Subjects within type | 1496.68 | 10 | — | — | — | — |
| conc | 4068.77 | 1.889 | 101.32 | < .001 | 0.9102 | 0.6819 |
| type × conc | 374.42 | 1.889 | 9.324 | .002 | 0.4825 | 0.1648 |
| conc × subjects within type | 401.57 | 18.889 | — | — | — | — |
Cell means
| type | conc | n | Mean | SE | CI low | CI high |
|---|---|---|---|---|---|---|
| Quebec | 95 | 6 | 14.067 | 1.038 | 11.399 | 16.735 |
| Quebec | 175 | 6 | 27.083 | 1.686 | 22.750 | 31.417 |
| Quebec | 250 | 6 | 35.933 | 1.403 | 32.328 | 39.539 |
| Quebec | 350 | 6 | 38.083 | 1.415 | 34.447 | 41.720 |
| Quebec | 500 | 6 | 38.133 | 1.521 | 34.224 | 42.042 |
| Quebec | 675 | 6 | 39.500 | 1.209 | 36.391 | 42.609 |
| Quebec | 1000 | 6 | 42 | 1.068 | 39.254 | 44.746 |
| Mississippi | 95 | 6 | 10.450 | 0.5982 | 8.912 | 11.988 |
| Mississippi | 175 | 6 | 17.483 | 1.538 | 13.530 | 21.437 |
| Mississippi | 250 | 6 | 21.817 | 2.781 | 14.669 | 28.964 |
| Mississippi | 350 | 6 | 23.250 | 3.125 | 15.218 | 31.282 |
| Mississippi | 500 | 6 | 23.617 | 3.303 | 15.127 | 32.107 |
| Mississippi | 675 | 6 | 24.400 | 3.012 | 16.657 | 32.143 |
| Mississippi | 1000 | 6 | 25.167 | 3.205 | 16.928 | 33.405 |
- type between subjects (2 groups), conc within (7 levels); sphericity correction: Greenhouse–Geisser.
interaction: F(1.89, 18.89) = 9.32, p = .002
- p (interaction)
- .002
- ε applied
- 0.3148
Effect size
- Partial η² (interaction) 0.4825
- Generalized η² (interaction) 0.1648
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sphericity — Mauchly's W = 0.000, p < .001; ε_GG = 0.315, ε_HF = 0.386. The Greenhouse–Geisser correction is applied.
- Equal variances between groups — Brown–Forsythe on the subject means: F = 7.57, p = .020.
- Normality of residuals — Shapiro–Wilk on the within-subject residuals: p = .847.
- Complete subjects — 12 subjects have a value for every condition.
Mixed ANOVA (Type III; within-subject df corrected)
| Source | SS | df | F | p | η²p | η²G |
|---|---|---|---|---|---|---|
| type | 3365.53 | 1 | 22.487 | < .001 | 0.6922 | 0.6394 |
| Subjects within type | 1496.68 | 10 | — | — | — | — |
| conc | 4068.77 | 1.889 | 101.32 | < .001 | 0.9102 | 0.6819 |
| type × conc | 374.42 | 1.889 | 9.324 | .002 | 0.4825 | 0.1648 |
| conc × subjects within type | 401.57 | 18.889 | — | — | — | — |
Cell means
| type | conc | n | Mean | SE | CI low | CI high |
|---|---|---|---|---|---|---|
| Quebec | 95 | 6 | 14.067 | 1.038 | 11.399 | 16.735 |
| Quebec | 175 | 6 | 27.083 | 1.686 | 22.750 | 31.417 |
| Quebec | 250 | 6 | 35.933 | 1.403 | 32.328 | 39.539 |
| Quebec | 350 | 6 | 38.083 | 1.415 | 34.447 | 41.720 |
| Quebec | 500 | 6 | 38.133 | 1.521 | 34.224 | 42.042 |
| Quebec | 675 | 6 | 39.500 | 1.209 | 36.391 | 42.609 |
| Quebec | 1000 | 6 | 42 | 1.068 | 39.254 | 44.746 |
| Mississippi | 95 | 6 | 10.450 | 0.5982 | 8.912 | 11.988 |
| Mississippi | 175 | 6 | 17.483 | 1.538 | 13.530 | 21.437 |
| Mississippi | 250 | 6 | 21.817 | 2.781 | 14.669 | 28.964 |
| Mississippi | 350 | 6 | 23.250 | 3.125 | 15.218 | 31.282 |
| Mississippi | 500 | 6 | 23.617 | 3.303 | 15.127 | 32.107 |
| Mississippi | 675 | 6 | 24.400 | 3.012 | 16.657 | 32.143 |
| Mississippi | 1000 | 6 | 25.167 | 3.205 | 16.928 | 33.405 |
- type between subjects (2 groups), conc within (7 levels); sphericity correction: Greenhouse–Geisser.
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
- Co2 typeco2_long · condition: conc · group: type · outcome: uptake · subject: plant
- Co2 treatment ggco2_long · condition: conc · group: treatment · outcome: uptake · subject: plant
- Unbalanced teamsrounding_teams · condition: base method · group: team · outcome: time · subject: player
- Degenerate constantco2_long · condition: conc · group: type · outcome: uptake · subject: plant
- Degenerate single levelco2_long · condition: conc · group: type · outcome: uptake · subject: plant
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
- Factorial designs, covariates, multivariate (ANCOVA, MANOVA) · Statistics Guide · B — Compare groups
- Sphericity · Statistics Guide · Step 2 — Check assumptions
- Interactions · Statistics Guide · Additional considerations
What you need
- Subject IDcategorical · 1 column
- Identifies each subject, so their repeated measurements are linked.
- Condition (within)categorical / boolean · 1 column · 2–20 levels
- The within-subject factor: each subject is measured under every condition.
- Group (between)categorical / boolean · 1 column · 2–10 levels
- Each subject belongs to exactly one group.
- Outcomenumeric · 1 column
- The numeric variable you are analyzing.
Choices you make
assumptions
- Sphericity correctiondefault auto
Correction to df when sphericity fails. Automatic picks Huynh–Feldt when ε_GG ≥ .75, else Greenhouse–Geisser.
- 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.
hypothesis
- Confidence level (cell means)default 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 on the pooled within-group covariance; corrections apply to the within and interaction effects.
Equal variances between groups
Brown–Forsythe test on the subject means.
Normality of residuals
Shapiro–Wilk on the within-subject residuals.
Complete subjects
Subjects missing a condition are left out; duplicate cells are averaged.
- If violated → Linear mixed model (keeps incomplete subjects) — Keeps subjects with a missing condition; random intercepts per subject. Changes the question: Effects come from all observed measurements (valid when data are missing at random), not from complete subjects only.
What it reports
- Tests: Between-groups effect
- Tests: Within-subjects effect
- Tests: Group × condition interaction
- f_between
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- df_between
- How much independent information is left to estimate variability after fitting the model.
- df_subjects
- How much independent information is left to estimate variability after fitting the model.
- p_between
- How surprising your data would be if the null hypothesis were true, as a probability.
- f_within
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- df_within
- How much independent information is left to estimate variability after fitting the model.
- df_error
- How much independent information is left to estimate variability after fitting the model.
- p_within
- How surprising your data would be if the null hypothesis were true, as a probability.
- f_interaction
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- df_interaction
- How much independent information is left to estimate variability after fitting the model.
- p_interaction
- 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 ε.
- 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 ε.
- 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_between
- Variance explained by an effect relative to that effect plus error, ignoring other effects in the model.
- eta_g_between
- Share of variance explained by an effect, defined so it compares across within- and between-subject designs.
- eta_p_within
- Variance explained by an effect relative to that effect plus error, ignoring other effects in the model.
- eta_g_within
- Share of variance explained by an effect, defined so it compares across within- and between-subject designs.
- eta_p_interaction
- Variance explained by an effect relative to that effect plus error, ignoring other effects in the model.
- eta_g_interaction
- Share of variance explained by an effect, defined so it compares across within- and between-subject designs.
- 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.
- g
- The mean difference divided by the pooled SD, multiplied by a small-sample correction J that removes Cohen's d's upward bias.
- 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 ε.
- between_name
- Name of the between-subjects factor column: each subject belongs to exactly one of its groups.
- within_name
- Name of the within-subjects factor column: each subject is measured at every one of its levels.
- n_dropped_subjects
- How many independent units the analysis used; it sets precision and power.
- levene_p
- Tests whether groups have equal variances; the Brown–Forsythe version uses medians and resists skew.
- sw_p_resid
- A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
- 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[<group> | <condition>]
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.
- Twin implementation (codesplash.stats.anova.rm_mixed ↔ cs_rm_mixed); equals aov(y ~ B*A + Error(subject/A)) for balanced groups and car::Anova(type = 3) semantics for unequal groups.
The exact script CodeSplash ran for example “Co2 type” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mixed (split-plot) ANOVA — one between, one within factor
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.mixed 1.1.1 · spec 055cff69ad34baef
# Dataset: co2_long (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
# %% Data
df = pd.read_parquet("tests/parity/fixtures/co2_long.parquet", columns=["plant", "conc", "type", "uptake"])
n_input = len(df)
df["plant"] = pd.Categorical(df["plant"], categories=["Qn1", "Qn2", "Qn3", "Qc1", "Qc3", "Qc2", "Mn3", "Mn2", "Mn1", "Mc2", "Mc3", "Mc1"]) # stored level order
df["conc"] = pd.Categorical(df["conc"], categories=["95", "175", "250", "350", "500", "675", "1000"]) # stored level order
df["type"] = pd.Categorical(df["type"], categories=["Quebec", "Mississippi"]) # stored level order
df = df.dropna(subset=["plant", "conc", "type", "uptake"]) # listwise deletion over the analysis columns
df["plant"] = df["plant"].cat.remove_unused_categories()
df["conc"] = df["conc"].cat.remove_unused_categories()
df["type"] = df["type"].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, ["plant", "conc", "type", "uptake"]) # infinite values stop the run (registry/errors.yaml)
# %% Wide format: one row per subject, one column per condition
subj, cond, y = "plant", "conc", "uptake"
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)
# %% Between-subjects factor: one level per subject
gcol = "type"
gsets = df.groupby(subj, observed=True)[gcol].agg(lambda s: sorted(set(s.astype(str))))
mixed = [str(s) for s, v in gsets.items() if len(v) > 1]
if mixed:
raise ValueError(f"Each subject must belong to one {gcol} level; {', '.join(mixed[:5])} have several")
glevels = [str(x) for x in df[gcol].cat.categories]
grp = np.array([gsets[s][0] for s in complete.index])
present = [lv for lv in glevels if (grp == lv).any()]
if len(present) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=gcol, min=2, k=len(present))
for lv in present: # complete subjects per group
if (grp == lv).sum() < 2:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=lv, n=int((grp == lv).sum()))
# %% Test
correction = "auto"
conf = 0.95
# No error variation within subjects (every subject in a group changes by the same amount): the F ratios are undefined.
resid0 = np.vstack([Y[grp == lv] - Y[grp == lv].mean(axis=1, keepdims=True) - Y[grp == lv].mean(axis=0, keepdims=True) + Y[grp == lv].mean()
for lv in present])
if float((resid0**2).sum()) <= 1e-12 * float(((Y - Y.mean()) ** 2).sum()):
cs.cs_error("CS_E_UNDEFINED", what="Mixed ANOVA",
reason="every subject in a group changes by the same amount between conditions, so there is no error variation to test against")
r = csa.rm_mixed(Y, grp) # Type III split-plot ANOVA (twin of R's cs_rm_mixed)
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]
p_within = float(stats.f.sf(r["f_a"], r["df_a"] * epsilon, r["df_e"] * epsilon))
p_inter = float(stats.f.sf(r["f_ab"], r["df_ab"] * epsilon, r["df_e"] * epsilon))
labels = {"none": "none", "gg": "Greenhouse–Geisser", "hf": "Huynh–Feldt", "lb": "lower-bound"}
# %% Assumptions
assumptions = []
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; ε_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 "")})
sm = Y.mean(axis=1)
lev = stats.levene(*[sm[grp == lv] for lv in present], center="median")
assumptions.append({"key": "equal_variance", "label": "Equal variances between groups", "status": "warn" if lev.pvalue < 0.05 else "pass",
"statistic": float(lev.statistic), "p": float(lev.pvalue),
"detail": f"Brown–Forsythe on the subject means: F = {lev.statistic:.2f}, {cs.fmt_p(lev.pvalue)}."})
cell = np.vstack([Y[grp == lv].mean(axis=0) for lv in present])
gidx = np.array([present.index(v) for v in grp])
resid = Y - cell[gidx] - (sm - np.array([sm[grp == lv].mean() for lv in present])[gidx])[:, None]
sw_p = float(stats.shapiro(resid.ravel()).pvalue) if 3 <= resid.size <= 5000 else None
assumptions.append({"key": "normality", "label": "Normality of residuals",
"status": "info" if sw_p is None else ("pass" if sw_p >= 0.05 else ("warn" if n_subj < 30 else "info")),
"detail": "Too few (or too many) residuals for Shapiro–Wilk." if sw_p is None else f"Shapiro–Wilk on the within-subject residuals: {cs.fmt_p(sw_p)}."})
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
cells = []
for lv in present:
block = Y[grp == lv]
nj = len(block)
q = stats.t.ppf(0.5 + conf / 2, nj - 1)
for j, c in enumerate(conditions):
m, se = float(block[:, j].mean()), float(block[:, j].std(ddof=1) / np.sqrt(nj))
cells.append({"group": lv, "condition": c, "n": nj, "mean": m, "se": se, "ci_low": m - q * se, "ci_high": m + q * se})
values = {
"f_between": r["f_b"], "df_between": r["df_b"], "df_subjects": r["df_sb"], "p_between": r["p_b"],
"f_within": r["f_a"], "df_within": r["df_a"] * epsilon, "df_error": r["df_e"] * epsilon, "p_within": p_within,
"f_interaction": r["f_ab"], "df_interaction": r["df_ab"] * epsilon, "p_interaction": p_inter, "epsilon": epsilon,
"gg_epsilon": r["gg"], "hf_epsilon": r["hf"], "mauchly_w": r["mauchly_w"], "mauchly_p": r["mauchly_p"],
"eta_p_between": r["eta_p_b"], "eta_g_between": r["eta_g_b"], "eta_p_within": r["eta_p_a"], "eta_g_within": r["eta_g_a"],
"eta_p_interaction": r["eta_p_ab"], "eta_g_interaction": r["eta_g_ab"], "n_subjects": n_subj, "k": k, "g": len(present),
"correction": applied, "correction_label": labels[applied], "between_name": gcol, "within_name": cond,
"n_dropped_subjects": n_dropped_subjects, "levene_p": float(lev.pvalue), "sw_p_resid": sw_p,
}
for c_ in cells:
values[f"mean[{c_['group']} | {c_['condition']}]"] = c_["mean"]
rows = [
{"source": gcol, "ss": r["ss_b"], "df": r["df_b"], "f": r["f_b"], "p": r["p_b"], "eta_p": r["eta_p_b"], "eta_g": r["eta_g_b"]},
{"source": f"Subjects within {gcol}", "ss": r["ss_sb"], "df": r["df_sb"]},
{"source": cond, "ss": r["ss_a"], "df": r["df_a"] * epsilon, "f": r["f_a"], "p": p_within, "eta_p": r["eta_p_a"], "eta_g": r["eta_g_a"]},
{"source": f"{gcol} × {cond}", "ss": r["ss_ab"], "df": r["df_ab"] * epsilon, "f": r["f_ab"], "p": p_inter, "eta_p": r["eta_p_ab"], "eta_g": r["eta_g_ab"]},
{"source": f"{cond} × subjects within {gcol}", "ss": r["ss_e"], "df": r["df_e"] * epsilon},
]
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
values["max_interaction_order"] = 2
cs.publish({
"method": "anova.mixed",
"methodVersion": "1.1.1",
"title": f"Mixed ANOVA ({gcol} × {cond})",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n_subj,
"summary": f"{gcol}: F = {r['f_b']:.2f}, {cs.fmt_p(r['p_b'])}; {cond}: F = {r['f_a']:.2f}, {cs.fmt_p(p_within)}; interaction: F = {r['f_ab']:.2f}, {cs.fmt_p(p_inter)}.",
"apa": f"interaction: F({cs.fmt_num(r['df_ab'] * epsilon)}, {cs.fmt_num(r['df_e'] * epsilon)}) = {cs.fmt_num(r['f_ab'])}, {cs.fmt_p(p_inter)}",
"statistics": [{"key": "p_interaction", "label": "p (interaction)", "value": p_inter, "format": "p"}, {"key": "epsilon", "label": "ε applied", "value": epsilon}],
"tables": [
{"key": "anova", "title": "Mixed ANOVA (Type III; within-subject df corrected)" if applied != "none" else "Mixed ANOVA (Type III)", "columns": [
{"key": "source", "label": "Source", "type": "string"}, {"key": "ss", "label": "SS", "type": "number"},
{"key": "df", "label": "df", "type": "number"}, {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "eta_p", "label": "η²p", "type": "number"}, {"key": "eta_g", "label": "η²G", "type": "number"}], "rows": rows},
{"key": "cell_means", "title": "Cell means", "columns": [
{"key": "group", "label": gcol, "type": "string"}, {"key": "condition", "label": cond, "type": "string"},
{"key": "n", "label": "n", "type": "integer"}, {"key": "mean", "label": "Mean", "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": cells},
],
"effectSizes": [{"key": "eta_p_interaction", "label": "Partial η² (interaction)", "value": r["eta_p_ab"], "method": "SS / (SS + SS_error)"},
{"key": "eta_g_interaction", "label": "Generalized η² (interaction)", "value": r["eta_g_ab"], "method": "Olejnik & Algina (2003)"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{gcol} between subjects ({len(present)} groups), {cond} within ({k} levels); sphericity correction: {labels[applied]}."],
"values": values,
"charts": [cs.chart("cell-means", "emm-plot", f"Mean {y} by {cond} and {gcol}", {
"x": cs.col(cond, [c_["condition"] for c_ in cells], "categorical", levels=conditions),
"trace": cs.col(gcol, [c_["group"] for c_ in cells], "categorical", levels=present),
"mean": cs.col(f"Mean {y}", [c_["mean"] for c_ in cells], "numeric"),
"low": cs.col("CI low", [c_["ci_low"] for c_ in cells], "numeric"),
"high": cs.col("CI high", [c_["ci_high"] for c_ in cells], "numeric")})],
})
The exact script CodeSplash ran for example “Co2 type” · R version 4.5.1 (2025-06-13)
# Mixed (split-plot) ANOVA — one between, one within factor
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.mixed 1.1.1 · spec 055cff69ad34baef
# Dataset: co2_long (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/co2_long.parquet", col_select = c("plant", "conc", "type", "uptake")))
n_input <- nrow(df)
df[["plant"]] <- factor(df[["plant"]], levels = c("Qn1", "Qn2", "Qn3", "Qc1", "Qc3", "Qc2", "Mn3", "Mn2", "Mn1", "Mc2", "Mc3", "Mc1")) # stored level order
df[["conc"]] <- factor(df[["conc"]], levels = c("95", "175", "250", "350", "500", "675", "1000")) # stored level order
df[["type"]] <- factor(df[["type"]], levels = c("Quebec", "Mississippi")) # stored level order
df <- df[stats::complete.cases(df[c("plant", "conc", "type", "uptake")]), , 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("plant", "conc", "type", "uptake")) # infinite values stop the run (registry/errors.yaml)
# %% Wide format: one row per subject, one column per condition
subj <- "plant"
cond <- "conc"
y <- "uptake"
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)
# %% Between-subjects factor: one level per subject
gcol <- "type"
gsets <- tapply(as.character(df[[gcol]]), df[[subj]], function(v) sort(unique(v), method = "radix"), simplify = FALSE)
mixed <- names(gsets)[lengths(gsets) > 1]
if (length(mixed)) stop(sprintf("Each subject must belong to one %s level; %s have several", gcol, paste(head(mixed, 5), collapse = ", ")))
glevels <- levels(df[[gcol]])
grp <- vapply(subjects, function(s) gsets[[s]][1], "")
present <- glevels[glevels %in% grp]
if (length(present) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = gcol, min = 2, k = length(present))
for (lv in present) { # complete subjects per group
if (sum(grp == lv) < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = lv, n = sum(grp == lv))
}
# %% Test
correction <- "auto"
conf <- 0.95
# No error variation within subjects (every subject in a group changes by the same amount): the F ratios are undefined.
resid0 <- do.call(rbind, lapply(present, function(lv) {
Yg <- Y[grp == lv, , drop = FALSE]
sweep(sweep(Yg, 1, rowMeans(Yg)), 2, colMeans(Yg)) + mean(Yg)
}))
if (sum(resid0^2) <= 1e-12 * sum((Y - mean(Y))^2)) {
cs_error("CS_E_UNDEFINED", what = "Mixed ANOVA",
reason = "every subject in a group changes by the same amount between conditions, so there is no error variation to test against")
}
r <- cs_rm_mixed(Y, grp) # Type III split-plot ANOVA (twin of codesplash.stats.anova.rm_mixed)
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)
p_within <- pf(r$f_a, r$df_a * epsilon, r$df_e * epsilon, lower.tail = FALSE)
p_inter <- pf(r$f_ab, r$df_ab * epsilon, r$df_e * epsilon, lower.tail = FALSE)
labels <- c(none = "none", gg = "Greenhouse–Geisser", hf = "Huynh–Feldt", lb = "lower-bound")
# %% Assumptions
assumptions <- list()
if (k < 3) {
assumptions[[1]] <- list(key = "sphericity", label = "Sphericity", status = "pass", detail = "Always satisfied with two conditions.")
} else if (is.nan(r$mauchly_p)) {
assumptions[[1]] <- list(key = "sphericity", label = "Sphericity", status = "info", detail = sprintf("Mauchly's test needs more subjects; ε_GG = %.3f.", r$gg))
} else {
bad <- r$mauchly_p < 0.05
assumptions[[1]] <- 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 ""))
}
sm <- rowMeans(Y)
gm <- vapply(present, function(lv) mean(sm[grp == lv]), 0)
gfac <- factor(grp, levels = present)
z <- abs(sm - ave(sm, gfac, FUN = median))
lev <- oneway.test(z ~ gfac, var.equal = TRUE) # Brown-Forsythe on the subject means
lev_p <- lev$p.value
assumptions[[2]] <- list(key = "equal_variance", label = "Equal variances between groups", status = if (lev_p < 0.05) "warn" else "pass",
statistic = unname(lev$statistic), p = lev_p,
detail = sprintf("Brown–Forsythe on the subject means: F = %.2f, %s.", unname(lev$statistic), cs_fmt_p(lev_p)))
cell <- t(vapply(present, function(lv) colMeans(Y[grp == lv, , drop = FALSE]), numeric(k)))
gidx <- match(grp, present)
resid <- Y - cell[gidx, , drop = FALSE] - (sm - gm[gidx])
sw_p <- if (length(resid) >= 3 && length(resid) <= 5000) shapiro.test(as.vector(t(resid)))$p.value else NULL
assumptions[[3]] <- list(key = "normality", label = "Normality of residuals",
status = if (is.null(sw_p)) "info" else if (sw_p >= 0.05) "pass" else if (n_subj < 30) "warn" else "info",
detail = if (is.null(sw_p)) "Too few (or too many) residuals for Shapiro–Wilk." else sprintf("Shapiro–Wilk on the within-subject residuals: %s.", cs_fmt_p(sw_p)))
assumptions[[4]] <- 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
cells <- do.call(rbind, lapply(present, function(lv) {
block <- Y[grp == lv, , drop = FALSE]
nj <- nrow(block)
q <- qt(0.5 + conf / 2, nj - 1)
m <- colMeans(block)
se <- apply(block, 2, sd) / sqrt(nj)
data.frame(group = lv, condition = conditions, n = nj, mean = m, se = se, ci_low = m - q * se, ci_high = m + q * se, stringsAsFactors = FALSE)
}))
rownames(cells) <- NULL
values <- list(
f_between = r$f_b, df_between = r$df_b, df_subjects = r$df_sb, p_between = r$p_b,
f_within = r$f_a, df_within = r$df_a * epsilon, df_error = r$df_e * epsilon, p_within = p_within,
f_interaction = r$f_ab, df_interaction = r$df_ab * epsilon, p_interaction = p_inter, epsilon = epsilon,
gg_epsilon = r$gg, hf_epsilon = r$hf, mauchly_w = r$mauchly_w, mauchly_p = r$mauchly_p,
eta_p_between = r$eta_p_b, eta_g_between = r$eta_g_b, eta_p_within = r$eta_p_a, eta_g_within = r$eta_g_a,
eta_p_interaction = r$eta_p_ab, eta_g_interaction = r$eta_g_ab, n_subjects = n_subj, k = k, g = length(present),
correction = applied, correction_label = labels[[applied]], between_name = gcol, within_name = cond,
n_dropped_subjects = n_dropped_subjects, levene_p = lev_p, sw_p_resid = sw_p
)
for (i in seq_len(nrow(cells))) values[[sprintf("mean[%s | %s]", cells$group[i], cells$condition[i])]] <- cells$mean[i]
rows <- list(
list(source = gcol, ss = r$ss_b, df = r$df_b, f = r$f_b, p = r$p_b, eta_p = r$eta_p_b, eta_g = r$eta_g_b),
list(source = sprintf("Subjects within %s", gcol), ss = r$ss_sb, df = r$df_sb),
list(source = cond, ss = r$ss_a, df = r$df_a * epsilon, f = r$f_a, p = p_within, eta_p = r$eta_p_a, eta_g = r$eta_g_a),
list(source = sprintf("%s × %s", gcol, cond), ss = r$ss_ab, df = r$df_ab * epsilon, f = r$f_ab, p = p_inter, eta_p = r$eta_p_ab, eta_g = r$eta_g_ab),
list(source = sprintf("%s × subjects within %s", cond, gcol), ss = r$ss_e, df = r$df_e * epsilon)
)
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
values$max_interaction_order <- 2
cs_publish(list(
method = "anova.mixed",
methodVersion = "1.1.1",
title = sprintf("Mixed ANOVA (%s × %s)", gcol, cond),
engine = cs_engine_info("stats", "nanoparquet"),
n = n_subj,
summary = sprintf("%s: F = %.2f, %s; %s: F = %.2f, %s; interaction: F = %.2f, %s.", gcol, r$f_b, cs_fmt_p(r$p_b), cond, r$f_a, cs_fmt_p(p_within),
r$f_ab, cs_fmt_p(p_inter)),
apa = sprintf("interaction: F(%s, %s) = %s, %s", cs_fmt_num(r$df_ab * epsilon), cs_fmt_num(r$df_e * epsilon), cs_fmt_num(r$f_ab), cs_fmt_p(p_inter)),
statistics = list(list(key = "p_interaction", label = "p (interaction)", value = p_inter, format = "p"), list(key = "epsilon", label = "ε applied", value = epsilon)),
tables = list(
list(key = "anova", title = if (applied != "none") "Mixed ANOVA (Type III; within-subject df corrected)" else "Mixed ANOVA (Type III)",
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 = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "eta_p", label = "η²p", type = "number"), list(key = "eta_g", label = "η²G", type = "number")),
rows = rows),
list(key = "cell_means", title = "Cell means",
columns = list(list(key = "group", label = gcol, type = "string"), list(key = "condition", label = cond, type = "string"),
list(key = "n", label = "n", type = "integer"), list(key = "mean", label = "Mean", 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 = cells)
),
effectSizes = list(list(key = "eta_p_interaction", label = "Partial η² (interaction)", value = r$eta_p_ab, method = "SS / (SS + SS_error)"),
list(key = "eta_g_interaction", label = "Generalized η² (interaction)", value = r$eta_g_ab, method = "Olejnik & Algina (2003)")),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("%s between subjects (%d groups), %s within (%d levels); sphericity correction: %s.", gcol, length(present), cond, k, labels[[applied]])),
values = values,
charts = list(cs_chart("cell-means", "emm-plot", sprintf("Mean %s by %s and %s", y, cond, gcol), list(
x = cs_col(cond, cells$condition, "categorical", levels = conditions),
trace = cs_col(gcol, cells$group, "categorical", levels = present),
mean = cs_col(paste("Mean", y), cells$mean, "numeric"),
low = cs_col("CI low", cells$ci_low, "numeric"),
high = cs_col("CI high", cells$ci_high, "numeric"))))
))
Sources
- Maxwell, S. E., Delaney, H. D., & Kelley, K. (2018). Designing experiments and analyzing data (3rd ed.), ch. 14.
- 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.
- Bakeman, R. (2005). Recommended effect size statistics for repeated measures designs. Behavior Research Methods, 37, 379–384.
From the CodeSplash method registry · anova.mixed v1.1.1.