BCompare groups · anova.factorial
Factorial ANOVA (two or three between factors)
Do two or more factors, and their interaction, affect the mean of an outcome?
Between-subjects ANOVA with two or three crossed factors: Type III sums of squares with sum-to-zero contrasts by default (Type II or sequential Type I as options), partial η² and ω², estimated marginal means with pairwise comparisons, and simple effects of the first factor within the levels of the second when the interaction matters.
A real result
Example “Warpbreaks balanced”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
interaction: F(2, 48) = 4.19, p = .021
- R²
- 0.3778
- Residual df
- 48
Effect size
- Partial η² (wool) 0.0727
- Partial η² (tension) 0.2615
- Partial η² (wool × tension) 0.1486
Plots
View data
| CI high | CI low | Mean breaks | tension | wool |
|---|---|---|---|---|
| 51.888 | 37.223 | 44.556 | L | A |
| 35.555 | 20.890 | 28.222 | L | B |
| 31.332 | 16.668 | 24 | M | A |
| 36.110 | 21.445 | 28.778 | M | B |
| 31.888 | 17.223 | 24.556 | H | A |
| 26.110 | 11.445 | 18.778 | H | B |
Assumptions
- Normality of residuals — Shapiro–Wilk on the residuals: p = .816.
- Equal variances across cells — Brown–Forsythe F = 2.89, p = .023 across 6 cells.
- Balanced design — 6 cells with 9 observations each.
ANOVA (Type III sums of squares)
| Source | SS | df | MS | F | p | η²p | ω²p |
|---|---|---|---|---|---|---|---|
| wool | 450.67 | 1 | 450.67 | 3.765 | .058 | 0.0727 | 0.0487 |
| tension | 2034.26 | 2 | 1017.13 | 8.498 | < .001 | 0.2615 | 0.2173 |
| wool × tension | 1002.78 | 2 | 501.39 | 4.189 | .021 | 0.1486 | 0.1056 |
| Residual | 5745.11 | 48 | 119.69 | — | — | — | — |
Estimated marginal means
| Factor | Level | EMM | SE | CI low | CI high |
|---|---|---|---|---|---|
| wool | A | 31.037 | 2.105 | 26.804 | 35.270 |
| wool | B | 25.259 | 2.105 | 21.026 | 29.493 |
| tension | L | 36.389 | 2.579 | 31.204 | 41.574 |
| tension | M | 26.389 | 2.579 | 21.204 | 31.574 |
| tension | H | 21.667 | 2.579 | 16.482 | 26.851 |
Pairwise comparisons of marginal means (Tukey adjustment)
| Factor | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| wool | A - B | 5.778 | 2.978 | 1.940 | .058 | −0.2090 | 11.765 |
| tension | L - M | 10.000 | 3.647 | 2.742 | .023 | 1.180 | 18.820 |
| tension | L - H | 14.722 | 3.647 | 4.037 | < .001 | 5.903 | 23.542 |
| tension | M - H | 4.722 | 3.647 | 1.295 | .405 | −4.097 | 13.542 |
Simple effects of wool within tension
| Effect | F | df1 | df2 | p |
|---|---|---|---|---|
| wool | tension=L | 10.030 | 1 | 48 | .003 |
| wool | tension=M | 0.8582 | 1 | 48 | .359 |
| wool | tension=H | 1.255 | 1 | 48 | .268 |
Pairwise comparisons of wool within tension
| Within | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| tension=L | A - B | 16.333 | 5.157 | 3.167 | .003 | 5.964 | 26.703 |
| tension=M | A - B | −4.778 | 5.157 | −0.9264 | .359 | −15.147 | 5.592 |
| tension=H | A - B | 5.778 | 5.157 | 1.120 | .268 | −4.592 | 16.147 |
- Model: breaks ~ wool * tension with sum-to-zero contrasts; marginal means weight the cells equally.
interaction: F(2, 48) = 4.19, p = .021
- R²
- 0.3778
- Residual df
- 48
Effect size
- Partial η² (wool) 0.0727
- Partial η² (tension) 0.2615
- Partial η² (wool × tension) 0.1486
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of residuals — Shapiro–Wilk on the residuals: p = .816.
- Equal variances across cells — Brown–Forsythe F = 2.89, p = .023 across 6 cells.
- Balanced design — 6 cells with 9 observations each.
ANOVA (Type III sums of squares)
| Source | SS | df | MS | F | p | η²p | ω²p |
|---|---|---|---|---|---|---|---|
| wool | 450.67 | 1 | 450.67 | 3.765 | .058 | 0.0727 | 0.0487 |
| tension | 2034.26 | 2 | 1017.13 | 8.498 | < .001 | 0.2615 | 0.2173 |
| wool × tension | 1002.78 | 2 | 501.39 | 4.189 | .021 | 0.1486 | 0.1056 |
| Residual | 5745.11 | 48 | 119.69 | — | — | — | — |
Estimated marginal means
| Factor | Level | EMM | SE | CI low | CI high |
|---|---|---|---|---|---|
| wool | A | 31.037 | 2.105 | 26.804 | 35.270 |
| wool | B | 25.259 | 2.105 | 21.026 | 29.493 |
| tension | L | 36.389 | 2.579 | 31.204 | 41.574 |
| tension | M | 26.389 | 2.579 | 21.204 | 31.574 |
| tension | H | 21.667 | 2.579 | 16.482 | 26.851 |
Pairwise comparisons of marginal means (Tukey adjustment)
| Factor | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| wool | A - B | 5.778 | 2.978 | 1.940 | .058 | −0.2090 | 11.765 |
| tension | L - M | 10.000 | 3.647 | 2.742 | .023 | 1.180 | 18.820 |
| tension | L - H | 14.722 | 3.647 | 4.037 | < .001 | 5.903 | 23.542 |
| tension | M - H | 4.722 | 3.647 | 1.295 | .405 | −4.097 | 13.542 |
Simple effects of wool within tension
| Effect | F | df1 | df2 | p |
|---|---|---|---|---|
| wool | tension=L | 10.030 | 1 | 48 | .003 |
| wool | tension=M | 0.8582 | 1 | 48 | .359 |
| wool | tension=H | 1.255 | 1 | 48 | .268 |
Pairwise comparisons of wool within tension
| Within | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| tension=L | A - B | 16.333 | 5.157 | 3.167 | .003 | 5.964 | 26.703 |
| tension=M | A - B | −4.778 | 5.157 | −0.9264 | .359 | −15.147 | 5.592 |
| tension=H | A - B | 5.778 | 5.157 | 1.120 | .268 | −4.592 | 16.147 |
- Model: breaks ~ wool * tension with sum-to-zero contrasts; marginal means weight the cells equally.
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
- Warpbreaks balancedwarpbreaks · factors: wool, tension · outcome: breaks
- Toothgrowth type2toothgrowth · factors: supp, dose_f · outcome: len
- Mtcars unbalancedmtcars · factors: am_f, cyl_f · outcome: mpg
- Three factors type1co2_long · factors: type, treatment, conc · outcome: uptake
- Degenerate constantwarpbreaks · factors: wool, tension · outcome: breaks
- Degenerate single levelwarpbreaks · factors: wool, tension · outcome: breaks
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Factorial designs, covariates, multivariate (ANCOVA, MANOVA) · Statistics Guide · B — Compare groups
- Normality (per group, differences or residuals) · Statistics Guide · Step 2 — Check assumptions
- Equal variance · Statistics Guide · Step 2 — Check assumptions
- Multiple comparisons · Statistics Guide · Additional considerations
- Interactions · Statistics Guide · Additional considerations
- Regression (linear, GLM), ANOVA, t-tests, chi-square · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric · 1 column
- The numeric variable you are analyzing.
- Factorscategorical / boolean · 2–3 columns · 2–20 levels
- Two or three crossed between-subjects factors; every combination of levels needs data.
Choices you make
options
- Sums of squaresdefault 3
Identical for balanced designs. Type III tests each effect adjusted for all others; Type II respects marginality.
- Type III (sum-to-zero contrasts)(default) — Tests each term after all the others, with sum-to-zero contrasts; the usual choice when interactions are in the model.
- Type II (hierarchical) — Tests each main effect after the other main effects, not their interactions; more powerful when there's no interaction.
- Type I (sequential, in factor order) — Tests terms in order, so factor order changes results with unbalanced data; pick it when the order has meaning.
posthoc
- Compare estimated marginal meansdefault on
After the overall test, compare each pair of groups, with p-values adjusted for the number of comparisons.
- Adjustmentdefault tukey
How pairwise p-values are corrected for multiple comparisons. Tukey suits all pairs of means; Holm works for any set.
- Tukey(default) — Compares all pairs using the studentized range; the standard for all pairwise comparisons of means.
- Holm — Controls the chance of any false positive; valid under any dependence, and better than Bonferroni.
- Bonferroni — Multiplies each p by the number of comparisons; the plainest and strictest choice.
- Šidák — A touch less strict than Bonferroni; exact when the comparisons are independent.
- Scheffé — Protects every possible contrast, not only pairs; wide, so pick it for comparisons chosen after seeing the data.
- None — Reports raw p-values; use it for one planned comparison, or say plainly that results are exploratory.
- Simple effects of the first factordefault auto
F tests and pairwise comparisons of the first factor within each level of the second.
- When the interaction is significant(default) — Runs them when the interaction is significant; the usual choice.
- Always — Runs them every time; pick it when you planned the comparison in advance.
- Never — Skips them; pick it when you need only the main effects and the interaction.
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.
Normality of residuals
Shapiro–Wilk on the model residuals.
Equal variances across cells
Brown–Forsythe test across the factor-level combinations.
Balanced design
With unequal cell sizes the type of sums of squares matters.
Independent observationsNot checked from data: state why it holds
What it reports
- Tests: Main effect of the first factor
- Tests: Main effect of the second factor
- Tests: Interaction of the first two factors
- f_a
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- df_a
- How much independent information is left to estimate variability after fitting the model.
- p_a
- How surprising your data would be if the null hypothesis were true, as a probability.
- eta_p_a
- Variance explained by an effect relative to that effect plus error, ignoring other effects in the model.
- f_b
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- df_b
- How much independent information is left to estimate variability after fitting the model.
- p_b
- How surprising your data would be if the null hypothesis were true, as a probability.
- eta_p_b
- Variance explained by an effect relative to that effect plus error, ignoring other effects in the model.
- f_ab
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- df_ab
- How much independent information is left to estimate variability after fitting the model.
- p_ab
- How surprising your data would be if the null hypothesis were true, as a probability.
- eta_p_ab
- Variance explained by an effect relative to that effect plus error, ignoring other effects in the model.
- ss_resid
- Total squared distance from a mean. ANOVA splits it between sources to show where the variation comes from.
- df_resid
- How much independent information is left to estimate variability after fitting the model.
- r2
- The share of the outcome's variance explained by the model, from 0 to 1.
- n
- How many independent units the analysis used; it sets precision and power.
- n_cells
- How many independent units the analysis used; it sets precision and power.
- min_cell
- Observations in the smallest combination of factor levels. A very small cell gives little information about that combination.
- max_cell
- Observations in the largest combination of factor levels. It equals the smallest cell size when the design is balanced.
- sw_p_resid
- A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
- levene_f
- Tests whether groups have equal variances; the Brown–Forsythe version uses medians and resists skew.
- levene_p
- Tests whether groups have equal variances; the Brown–Forsythe version uses medians and resists skew.
- factor_a
- Name of the first factor column; its main effect is the first one reported (factor A).
- factor_b
- Name of the second factor column; its main effect is the second one reported (factor B).
- ss_type
- Ways to split variance among correlated factors in unbalanced ANOVA; they answer different questions.
- 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.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
Per group, level or term: f[<term>], p[<term>], df[<term>], ss[<term>], eta_p[<term>], omega_p[<term>], emm[<factor>: <level>], diff[<factor>: <a> - <b>], p_adj[<factor>: <a> - <b>], simple_f[<a> | <b>=<level>], simple_p[…]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, statsmodels, patsy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Tukey-adjusted p-values use the studentized range (scipy numeric integration vs R ptukey AS 190; ~1e-6, see anova.oneway).
- Type III: statsmodels anova_lm(typ=3) Wald tests on sum-coded blocks ≡ R drop1(fit, ~., test = 'F') with contr.sum (equal for OLS).
The exact script CodeSplash ran for example “Warpbreaks balanced” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Factorial ANOVA (two or three between factors)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.factorial 1.0.1 · spec bd868ff14ec993bd
# Dataset: warpbreaks (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
import statsmodels.formula.api as smf
from scipy import stats
import codesplash as cs
from codesplash.stats import anova as csa
from codesplash.stats import emm
# %% Data
df = pd.read_parquet("tests/parity/fixtures/warpbreaks.parquet", columns=["breaks", "wool", "tension"])
n_input = len(df)
df["wool"] = pd.Categorical(df["wool"], categories=["A", "B"]) # stored level order
df["tension"] = pd.Categorical(df["tension"], categories=["L", "M", "H"]) # stored level order
df = df.dropna(subset=["breaks", "wool", "tension"]) # listwise deletion over the analysis columns
df["wool"] = df["wool"].cat.remove_unused_categories()
df["tension"] = df["tension"].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, ["breaks", "wool", "tension"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
y = "breaks"
factor_cols = ["wool", "tension"]
safe = [f"f{i + 1}" for i in range(len(factor_cols))] # formula-safe names
name = dict(zip(safe, factor_cols))
d = pd.DataFrame({"y": df[y].to_numpy(dtype=float)})
for s, c in zip(safe, factor_cols):
d[s] = pd.Categorical(df[c].astype(str), categories=[str(x) for x in df[c].cat.categories])
if len(d[s].cat.categories) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=c, min=2, k=len(d[s].cat.categories))
if d["y"].nunique() < 2: # a constant outcome leaves nothing to test (the F ratios would be 0/0)
cs.cs_error("CS_E_CONSTANT", column=y)
cells = d.groupby(safe, observed=False).size()
if (cells == 0).any():
empty = ["/".join(map(str, ix)) for ix in cells[cells == 0].index][:5]
raise ValueError(f"Every combination of factor levels needs data; empty cells: {', '.join(empty)}")
if len(d) < len(cells) + 1: # one value per cell leaves no residual degrees of freedom
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Factorial ANOVA", min=len(cells) + 1, n=len(d))
ss_cells = float(((d["y"] - d.groupby(safe, observed=True)["y"].transform("mean")) ** 2).sum())
if ss_cells <= 1e-12 * float(((d["y"] - d["y"].mean()) ** 2).sum()): # no variation inside the cells: every F ratio is undefined
cs.cs_error("CS_E_UNDEFINED", what="Factorial ANOVA", reason=f"{y} does not vary within any cell")
ss_type = "3"
conf = 0.95
alpha = 1 - conf
# Sum-to-zero contrasts (R: contr.sum) so Type III tests are meaningful; Types I/II do not depend on them.
fit = smf.ols("y ~ " + " * ".join(f"C({s}, Sum)" for s in safe), d).fit()
tab, ss_resid, df_resid = csa.anova_table(fit, int(ss_type))
N = len(d)
def term_label(term):
return " × ".join(name[s] for s in term.split(":"))
terms = []
for _, row in tab.iterrows():
f, dfe = row["f"], row["df"]
terms.append({"term": term_label(row["term"]), "key": row["term"], "ss": row["ss"], "df": dfe, "ms": row["ss"] / dfe, "f": f, "p": row["p"],
"eta_p": row["ss"] / (row["ss"] + ss_resid), "omega_p": dfe * (f - 1) / (dfe * (f - 1) + N)})
by_key = {t["key"]: t for t in terms}
r2 = float(fit.rsquared)
# %% Estimated marginal means and comparisons
adjust = "tukey"
emms, comps = [], []
for s in safe:
for _, e in emm.emmeans(fit, d, s, safe, [], conf=conf).iterrows():
emms.append({"factor": name[s], "level": str(e["level"]), "emm": e["emm"], "se": e["se"], "ci_low": e["ci_low"], "ci_high": e["ci_high"]})
if True:
for _, c in emm.contrasts(fit, d, s, safe, [], adjust=adjust, conf=conf).iterrows():
comps.append({"factor": name[s], "contrast": c["contrast"], "estimate": c["estimate"], "se": c["se"], "df": c["df"], "t": c["t"],
"p_adj": c["p_adj"], "ci_low": c["ci_low"], "ci_high": c["ci_high"]})
mode = "auto"
want_simple = mode == "always" or (mode == "auto" and by_key["f1:f2"]["p"] < alpha)
simple, simple_pairs = [], []
if want_simple:
for _, j in emm.joint_test(fit, d, "f1", safe, [], by="f2").iterrows():
simple.append({"effect": f"{name['f1']} | {name['f2']}={j['by']}", "f": j["f"], "df1": j["df1"], "df2": j["df2"], "p": j["p"]})
for _, c in emm.contrasts(fit, d, "f1", safe, [], by="f2", adjust=adjust, conf=conf).iterrows():
simple_pairs.append({"within": f"{name['f2']}={c['by']}", "contrast": c["contrast"], "estimate": c["estimate"], "se": c["se"],
"t": c["t"], "p_adj": c["p_adj"], "ci_low": c["ci_low"], "ci_high": c["ci_high"]})
cell_emm = emm.emmeans(fit, d, "f1", safe, [], by="f2", conf=conf)
# %% Assumptions
assumptions = []
resid = np.asarray(fit.resid, dtype=float)
sw_p = float(stats.shapiro(resid).pvalue) if 3 <= len(resid) <= 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."})
else:
bad = sw_p < 0.05
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": ("warn" if N < 60 else "info") if bad else "pass", "p": sw_p,
"detail": f"Shapiro–Wilk on the residuals: {cs.fmt_p(sw_p)}" + ("; consider a transformation or a robust method." if bad and N < 60 else "; the F tests are robust with this sample size." if bad else ".")})
cell_groups = [g["y"].to_numpy() for _, g in d.groupby(safe, observed=True)]
if min(len(x) for x in cell_groups) >= 2:
lev = stats.levene(*cell_groups, center="median") # Brown–Forsythe across cells
lev_f, lev_p = float(lev.statistic), float(lev.pvalue)
assumptions.append({"key": "equal_variance", "label": "Equal variances across cells", "status": "warn" if lev_p < 0.05 else "pass",
"statistic": lev_f, "p": lev_p,
"detail": f"Brown–Forsythe F = {lev_f:.2f}, {cs.fmt_p(lev_p)} across {len(cell_groups)} cells."})
else: # a cell with a single value: Brown–Forsythe is undefined (R's convention: two values per cell)
lev_f = lev_p = None
assumptions.append({"key": "equal_variance", "label": "Equal variances across cells", "status": "info",
"detail": "A cell has a single value, so the variances can't be compared across cells."})
sizes = cells.to_numpy()
balanced = sizes.min() == sizes.max()
assumptions.append({"key": "balance", "label": "Balanced design", "status": "pass" if balanced else "info",
"detail": f"{len(sizes)} cells with {sizes.min()} observations each." if balanced
else f"Cell sizes range from {sizes.min()} to {sizes.max()}; Type {ss_type} sums of squares are used."})
# %% Result
values = {"ss_resid": ss_resid, "df_resid": df_resid, "r2": r2, "n": N, "n_cells": int(len(sizes)), "min_cell": int(sizes.min()),
"max_cell": int(sizes.max()), "sw_p_resid": sw_p, "levene_f": lev_f, "levene_p": lev_p,
"factor_a": name["f1"], "factor_b": name["f2"], "ss_type": {"1": "I", "2": "II", "3": "III"}[ss_type]}
for short, key in (("a", "f1"), ("b", "f2"), ("ab", "f1:f2")):
t = by_key[key]
values.update({f"f_{short}": t["f"], f"df_{short}": t["df"], f"p_{short}": t["p"], f"eta_p_{short}": t["eta_p"]})
for t in terms:
for k_ in ("f", "p", "df", "ss", "eta_p", "omega_p"):
values[f"{k_}[{t['term']}]"] = t[k_]
for e in emms:
values[f"emm[{e['factor']}: {e['level']}]"] = e["emm"]
for c in comps:
values[f"diff[{c['factor']}: {c['contrast']}]"] = c["estimate"]
values[f"p_adj[{c['factor']}: {c['contrast']}]"] = c["p_adj"]
for sres in simple:
values[f"simple_f[{sres['effect']}]"] = sres["f"]
values[f"simple_p[{sres['effect']}]"] = sres["p"]
anova_rows = [{k_: t[k_] for k_ in ("term", "ss", "df", "ms", "f", "p", "eta_p", "omega_p")} for t in terms]
anova_rows.append({"term": "Residual", "ss": ss_resid, "df": df_resid, "ms": ss_resid / df_resid})
adj_label = {"tukey": "Tukey", "holm": "Holm", "bonferroni": "Bonferroni", "sidak": "Šidák", "scheffe": "Scheffé", "none": "no"}[adjust]
tables = [
{"key": "anova", "title": f"ANOVA (Type {values['ss_type']} sums of squares)", "columns": [
{"key": "term", "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": "eta_p", "label": "η²p", "type": "number"}, {"key": "omega_p", "label": "ω²p", "type": "number"}], "rows": anova_rows},
{"key": "emm", "title": "Estimated marginal means", "columns": [
{"key": "factor", "label": "Factor", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
{"key": "emm", "label": "EMM", "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": emms},
]
if comps:
tables.append({"key": "posthoc", "title": f"Pairwise comparisons of marginal means ({adj_label} adjustment)", "columns": [
{"key": "factor", "label": "Factor", "type": "string"}, {"key": "contrast", "label": "Contrast", "type": "string"},
{"key": "estimate", "label": "Difference", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"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": comps})
if simple:
tables.append({"key": "simple_effects", "title": f"Simple effects of {name['f1']} within {name['f2']}", "columns": [
{"key": "effect", "label": "Effect", "type": "string"}, {"key": "f", "label": "F", "type": "number"},
{"key": "df1", "label": "df1", "type": "number"}, {"key": "df2", "label": "df2", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}], "rows": simple})
tables.append({"key": "simple_pairs", "title": f"Pairwise comparisons of {name['f1']} within {name['f2']}", "columns": [
{"key": "within", "label": "Within", "type": "string"}, {"key": "contrast", "label": "Contrast", "type": "string"},
{"key": "estimate", "label": "Difference", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"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": simple_pairs})
ta, tb, tab_ = by_key["f1"], by_key["f2"], by_key["f1:f2"]
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
values["max_interaction_order"] = len(safe)
values["n_params"] = len(fit.params)
cs.publish({
"method": "anova.factorial",
"methodVersion": "1.0.1",
"title": f"Factorial ANOVA ({' × '.join(factor_cols)})",
"engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
"n": N,
"summary": f"{name['f1']}: F = {ta['f']:.2f}, {cs.fmt_p(ta['p'])}; {name['f2']}: F = {tb['f']:.2f}, {cs.fmt_p(tb['p'])}; interaction: F = {tab_['f']:.2f}, {cs.fmt_p(tab_['p'])}.",
"apa": f"interaction: F({cs.fmt_num(tab_['df'], 0)}, {cs.fmt_num(df_resid, 0)}) = {cs.fmt_num(tab_['f'])}, {cs.fmt_p(tab_['p'])}",
"statistics": [{"key": "r2", "label": "R²", "value": r2}, {"key": "df_resid", "label": "Residual df", "value": df_resid}],
"tables": tables,
"effectSizes": [{"key": f"eta_p_{s}", "label": f"Partial η² ({lab})", "value": by_key[k_]["eta_p"], "method": "SS_effect / (SS_effect + SS_residual)"}
for s, k_, lab in (("a", "f1", name["f1"]), ("b", "f2", name["f2"]), ("ab", "f1:f2", f"{name['f1']} × {name['f2']}"))],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Model: {y} ~ {' * '.join(factor_cols)} with sum-to-zero contrasts; marginal means weight the cells equally."],
"values": values,
"charts": [cs.chart("cell-means", "emm-plot", f"Estimated marginal means of {y}", {
"x": cs.col(name["f1"], [str(v) for v in cell_emm["level"]], "categorical", levels=[str(x) for x in d["f1"].cat.categories]),
"trace": cs.col(name["f2"], [str(v) for v in cell_emm["by"]], "categorical", levels=[str(x) for x in d["f2"].cat.categories]),
"mean": cs.col(f"Mean {y}", cell_emm["emm"].to_numpy(), "numeric"),
"low": cs.col("CI low", cell_emm["ci_low"].to_numpy(), "numeric"),
"high": cs.col("CI high", cell_emm["ci_high"].to_numpy(), "numeric")})],
})
The exact script CodeSplash ran for example “Warpbreaks balanced” · R version 4.5.1 (2025-06-13)
# Factorial ANOVA (two or three between factors)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.factorial 1.0.1 · spec bd868ff14ec993bd
# Dataset: warpbreaks (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/warpbreaks.parquet", col_select = c("breaks", "wool", "tension")))
n_input <- nrow(df)
df[["wool"]] <- factor(df[["wool"]], levels = c("A", "B")) # stored level order
df[["tension"]] <- factor(df[["tension"]], levels = c("L", "M", "H")) # stored level order
df <- df[stats::complete.cases(df[c("breaks", "wool", "tension")]), , 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("breaks", "wool", "tension")) # infinite values stop the run (registry/errors.yaml)
# %% Model
y <- "breaks"
factor_cols <- c("wool", "tension")
safe <- paste0("f", seq_along(factor_cols)) # formula-safe names
name <- stats::setNames(factor_cols, safe)
d <- data.frame(y = as.numeric(df[[y]]))
for (i in seq_along(safe)) {
d[[safe[i]]] <- factor(as.character(df[[factor_cols[i]]]), levels = levels(df[[factor_cols[i]]]))
if (nlevels(d[[safe[i]]]) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = factor_cols[i], min = 2, k = nlevels(d[[safe[i]]]))
}
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = y) # a constant outcome leaves nothing to test (the F ratios would be 0/0)
cells <- table(d[safe])
if (any(cells == 0)) {
idx <- which(cells == 0, arr.ind = TRUE)
empty <- apply(idx, 1, function(r) paste(vapply(seq_along(r), function(j) dimnames(cells)[[j]][r[j]], ""), collapse = "/"))
stop(sprintf("Every combination of factor levels needs data; empty cells: %s", paste(head(empty, 5), collapse = ", ")))
}
if (nrow(d) < length(cells) + 1) { # one value per cell leaves no residual degrees of freedom
cs_error("CS_E_TOO_FEW_ROWS", what = "Factorial ANOVA", min = length(cells) + 1, n = nrow(d))
}
ss_cells <- sum((d$y - ave(d$y, interaction(d[safe], drop = TRUE)))^2)
if (ss_cells <= 1e-12 * sum((d$y - mean(d$y))^2)) { # no variation inside the cells: every F ratio is undefined
cs_error("CS_E_UNDEFINED", what = "Factorial ANOVA", reason = sprintf("%s does not vary within any cell", y))
}
ss_type <- "3"
conf <- 0.95
alpha <- 1 - conf
# Sum-to-zero contrasts so Type III tests are meaningful; Types I/II do not depend on them.
fit <- lm(stats::as.formula(paste("y ~", paste(safe, collapse = " * "))), data = d,
contrasts = stats::setNames(rep(list("contr.sum"), length(safe)), safe))
tab <- cs_anova_table(fit, as.integer(ss_type))
ss_resid <- sum(residuals(fit)^2)
df_resid <- fit$df.residual
N <- nrow(d)
term_label <- function(term) paste(name[strsplit(term, ":", fixed = TRUE)[[1]]], collapse = " × ")
terms <- data.frame(term = vapply(tab$term, term_label, ""), key = tab$term, ss = tab$ss, df = tab$df, ms = tab$ss / tab$df,
f = tab$f, p = tab$p, stringsAsFactors = FALSE)
terms$eta_p <- terms$ss / (terms$ss + ss_resid)
terms$omega_p <- terms$df * (terms$f - 1) / (terms$df * (terms$f - 1) + N)
# report terms in the Python/patsy order (main effects, then interactions by order)
terms <- terms[order(lengths(strsplit(terms$key, ":", fixed = TRUE)), match(terms$key, tab$term)), ]
rownames(terms) <- NULL
by_key <- function(k) terms[terms$key == k, ]
r2 <- summary(fit)$r.squared
# %% Estimated marginal means and comparisons
adjust <- "tukey"
emms <- data.frame()
comps <- data.frame()
for (s in safe) {
e <- cs_emmeans(fit, d, s, safe, character(0), conf = conf)
emms <- rbind(emms, data.frame(factor = name[[s]], level = e$level, emm = e$emm, se = e$se, ci_low = e$ci_low, ci_high = e$ci_high,
stringsAsFactors = FALSE))
if (TRUE) {
cc <- cs_emm_contrasts(fit, d, s, safe, character(0), adjust = adjust, conf = conf)
comps <- rbind(comps, data.frame(factor = name[[s]], contrast = cc$contrast, estimate = cc$estimate, se = cc$se, df = cc$df, t = cc$t,
p_adj = cc$p_adj, ci_low = cc$ci_low, ci_high = cc$ci_high, stringsAsFactors = FALSE))
}
}
mode <- "auto"
want_simple <- mode == "always" || (mode == "auto" && by_key("f1:f2")$p < alpha)
simple <- data.frame()
simple_pairs <- data.frame()
if (want_simple) {
j <- cs_emm_joint_test(fit, d, "f1", safe, character(0), by = "f2")
simple <- data.frame(effect = sprintf("%s | %s=%s", name[["f1"]], name[["f2"]], j$by), f = j$f, df1 = j$df1, df2 = j$df2, p = j$p,
stringsAsFactors = FALSE)
cc <- cs_emm_contrasts(fit, d, "f1", safe, character(0), by = "f2", adjust = adjust, conf = conf)
simple_pairs <- data.frame(within = sprintf("%s=%s", name[["f2"]], cc$by), contrast = cc$contrast, estimate = cc$estimate, se = cc$se,
t = cc$t, p_adj = cc$p_adj, ci_low = cc$ci_low, ci_high = cc$ci_high, stringsAsFactors = FALSE)
}
cell_emm <- cs_emmeans(fit, d, "f1", safe, character(0), by = "f2", conf = conf)
# %% Assumptions
assumptions <- list()
res <- residuals(fit)
sw_p <- if (length(res) >= 3 && length(res) <= 5000) shapiro.test(res)$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 {
bad <- sw_p < 0.05
assumptions[[1]] <- list(key = "normality", label = "Normality of residuals",
status = if (bad) (if (N < 60) "warn" else "info") else "pass", p = sw_p,
detail = paste0(sprintf("Shapiro–Wilk on the residuals: %s", cs_fmt_p(sw_p)),
if (bad && N < 60) "; consider a transformation or a robust method."
else if (bad) "; the F tests are robust with this sample size." else "."))
}
cell <- interaction(d[safe], drop = TRUE, lex.order = TRUE)
z <- abs(d$y - ave(d$y, cell, FUN = median))
if (min(table(cell)) >= 2) {
lev <- oneway.test(z ~ cell, var.equal = TRUE) # Brown-Forsythe across cells
lev_f <- unname(lev$statistic)
lev_p <- lev$p.value
assumptions[[2]] <- list(key = "equal_variance", label = "Equal variances across cells", status = if (lev_p < 0.05) "warn" else "pass",
statistic = lev_f, p = lev_p, detail = sprintf("Brown–Forsythe F = %.2f, %s across %d cells.", lev_f, cs_fmt_p(lev_p), nlevels(cell)))
} else { # a cell with a single value: Brown-Forsythe is undefined (oneway.test needs two values per cell)
lev_f <- NULL
lev_p <- NULL
assumptions[[2]] <- list(key = "equal_variance", label = "Equal variances across cells", status = "info",
detail = "A cell has a single value, so the variances can't be compared across cells.")
}
sizes <- as.vector(cells)
balanced <- min(sizes) == max(sizes)
assumptions[[3]] <- list(key = "balance", label = "Balanced design", status = if (balanced) "pass" else "info",
detail = if (balanced) sprintf("%d cells with %d observations each.", length(sizes), min(sizes))
else sprintf("Cell sizes range from %d to %d; Type %s sums of squares are used.", min(sizes), max(sizes), ss_type))
# %% Result
values <- list(ss_resid = ss_resid, df_resid = df_resid, r2 = r2, n = N, n_cells = length(sizes), min_cell = min(sizes), max_cell = max(sizes),
sw_p_resid = sw_p, levene_f = lev_f, levene_p = lev_p, factor_a = name[["f1"]], factor_b = name[["f2"]],
ss_type = c("1" = "I", "2" = "II", "3" = "III")[[ss_type]])
for (pair in list(c("a", "f1"), c("b", "f2"), c("ab", "f1:f2"))) {
t_ <- by_key(pair[2])
values[[paste0("f_", pair[1])]] <- t_$f
values[[paste0("df_", pair[1])]] <- t_$df
values[[paste0("p_", pair[1])]] <- t_$p
values[[paste0("eta_p_", pair[1])]] <- t_$eta_p
}
for (i in seq_len(nrow(terms))) {
for (k_ in c("f", "p", "df", "ss", "eta_p", "omega_p")) values[[sprintf("%s[%s]", k_, terms$term[i])]] <- terms[[k_]][i]
}
for (i in seq_len(nrow(emms))) values[[sprintf("emm[%s: %s]", emms$factor[i], emms$level[i])]] <- emms$emm[i]
for (i in seq_len(nrow(comps))) {
values[[sprintf("diff[%s: %s]", comps$factor[i], comps$contrast[i])]] <- comps$estimate[i]
values[[sprintf("p_adj[%s: %s]", comps$factor[i], comps$contrast[i])]] <- comps$p_adj[i]
}
for (i in seq_len(nrow(simple))) {
values[[sprintf("simple_f[%s]", simple$effect[i])]] <- simple$f[i]
values[[sprintf("simple_p[%s]", simple$effect[i])]] <- simple$p[i]
}
anova_rows <- lapply(seq_len(nrow(terms)), function(i) as.list(terms[i, c("term", "ss", "df", "ms", "f", "p", "eta_p", "omega_p")]))
anova_rows[[length(anova_rows) + 1]] <- list(term = "Residual", ss = ss_resid, df = df_resid, ms = ss_resid / df_resid)
adj_label <- c(tukey = "Tukey", holm = "Holm", bonferroni = "Bonferroni", sidak = "Šidák", scheffe = "Scheffé", none = "no")[[adjust]]
tables <- list(
list(key = "anova", title = sprintf("ANOVA (Type %s sums of squares)", values$ss_type),
columns = list(list(key = "term", 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 = "eta_p", label = "η²p", type = "number"), list(key = "omega_p", label = "ω²p", type = "number")),
rows = anova_rows),
list(key = "emm", title = "Estimated marginal means",
columns = list(list(key = "factor", label = "Factor", type = "string"), list(key = "level", label = "Level", type = "string"),
list(key = "emm", label = "EMM", 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 = emms)
)
if (nrow(comps) > 0) {
tables[[length(tables) + 1]] <- list(key = "posthoc", title = sprintf("Pairwise comparisons of marginal means (%s adjustment)", adj_label),
columns = list(list(key = "factor", label = "Factor", type = "string"), list(key = "contrast", label = "Contrast", type = "string"),
list(key = "estimate", label = "Difference", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "t", label = "t", type = "number"), 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 = comps[, c("factor", "contrast", "estimate", "se", "df", "t", "p_adj", "ci_low", "ci_high")])
}
if (nrow(simple) > 0) {
tables[[length(tables) + 1]] <- list(key = "simple_effects", title = sprintf("Simple effects of %s within %s", name[["f1"]], name[["f2"]]),
columns = list(list(key = "effect", label = "Effect", type = "string"), list(key = "f", label = "F", type = "number"),
list(key = "df1", label = "df1", type = "number"), list(key = "df2", label = "df2", type = "number"),
list(key = "p", label = "p", type = "pvalue")), rows = simple)
tables[[length(tables) + 1]] <- list(key = "simple_pairs", title = sprintf("Pairwise comparisons of %s within %s", name[["f1"]], name[["f2"]]),
columns = list(list(key = "within", label = "Within", type = "string"), list(key = "contrast", label = "Contrast", type = "string"),
list(key = "estimate", label = "Difference", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "t", label = "t", type = "number"), 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 = simple_pairs)
}
ta <- by_key("f1")
tb <- by_key("f2")
tab_ <- by_key("f1:f2")
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
values$max_interaction_order <- length(safe)
values$n_params <- length(coef(fit))
cs_publish(list(
method = "anova.factorial",
methodVersion = "1.0.1",
title = sprintf("Factorial ANOVA (%s)", paste(factor_cols, collapse = " × ")),
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = sprintf("%s: F = %.2f, %s; %s: F = %.2f, %s; interaction: F = %.2f, %s.", name[["f1"]], ta$f, cs_fmt_p(ta$p), name[["f2"]], tb$f,
cs_fmt_p(tb$p), tab_$f, cs_fmt_p(tab_$p)),
apa = sprintf("interaction: F(%s, %s) = %s, %s", cs_fmt_num(tab_$df, 0), cs_fmt_num(df_resid, 0), cs_fmt_num(tab_$f), cs_fmt_p(tab_$p)),
statistics = list(list(key = "r2", label = "R²", value = r2), list(key = "df_resid", label = "Residual df", value = df_resid)),
tables = tables,
effectSizes = list(
list(key = "eta_p_a", label = sprintf("Partial η² (%s)", name[["f1"]]), value = ta$eta_p, method = "SS_effect / (SS_effect + SS_residual)"),
list(key = "eta_p_b", label = sprintf("Partial η² (%s)", name[["f2"]]), value = tb$eta_p, method = "SS_effect / (SS_effect + SS_residual)"),
list(key = "eta_p_ab", label = sprintf("Partial η² (%s × %s)", name[["f1"]], name[["f2"]]), value = tab_$eta_p, method = "SS_effect / (SS_effect + SS_residual)")
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Model: %s ~ %s with sum-to-zero contrasts; marginal means weight the cells equally.", y, paste(factor_cols, collapse = " * "))),
values = values,
charts = list(cs_chart("cell-means", "emm-plot", sprintf("Estimated marginal means of %s", y), list(
x = cs_col(name[["f1"]], cell_emm$level, "categorical", levels = levels(d$f1)),
trace = cs_col(name[["f2"]], cell_emm$by, "categorical", levels = levels(d$f2)),
mean = cs_col(paste("Mean", y), cell_emm$emm, "numeric"),
low = cs_col("CI low", cell_emm$ci_low, "numeric"),
high = cs_col("CI high", cell_emm$ci_high, "numeric"))))
))
Sources
- Maxwell, S. E., Delaney, H. D., & Kelley, K. (2018). Designing experiments and analyzing data (3rd ed.). Routledge.
- Searle, S. R., Speed, F. M., & Milliken, G. A. (1980). Population marginal means in the linear model. The American Statistician, 34, 216–221.
- Olejnik, S., & Algina, J. (2003). Generalized eta and omega squared statistics. Psychological Methods, 8, 434–447.
From the CodeSplash method registry · anova.factorial v1.0.1.