Type I, II and III sums of squares
Swap two predictors in an unbalanced ANOVA and R's anova() gives a different F. Learn what each type tests, and why generated code always names one.
What runs in CodeSplash
- STAT017Factorial ANOVA F tests Runs in CodeSplash
- Factorial ANOVA (two or three between factors) Verified in Python and R
You will be able to
- Explain why predictor order changes a Type I test
- Say what Type II and Type III test
- Choose a type on purpose and report it
Read first
Swap two lines
ReadDoes transmission affect fuel economy, allowing for the number of cylinders? In this unbalanced data, the two predictors are related. Fit the same two predictors in each order.
import pandas as pd
import statsmodels.formula.api as smf
from statsmodels.stats.anova import anova_lm
df = pd.read_csv("mtcars.csv")
anova_lm(smf.ols("mpg ~ am_f + cyl_f", df).fit())
# am_f F = 42.890
# cyl_f F = 24.158
anova_lm(smf.ols("mpg ~ cyl_f + am_f", df).fit())
# cyl_f F = 43.657
# am_f F = 3.892df <- read.csv("mtcars.csv")
anova(lm(mpg ~ am_f + cyl_f, df))
# am_f F = 42.890
# cyl_f F = 24.158
anova(lm(mpg ~ cyl_f + am_f, df))
# cyl_f F = 43.657
# am_f F = 3.892Same data, same model, and the transmission falls from to .
What changed?
PredictPredict first
Both models fit identically. Why did the for transmission change so much when the order changed?
Reveal
The question. Both functions default to Type I, sequential sums of squares: each term is tested after the ones listed before it. First in line, am_f gets credit for everything it shares with cylinders. Last in line, it's tested after cylinders have had their turn, and the shared part has gone.
The three types
Read- Type I (sequential): each term after those before it. Order matters.
- Type II (hierarchical): each main effect after the other main effects, ignoring interactions containing it.
- Type III: each term after all others, including interactions, with sum-to-zero coding.
With balanced data, where the factors are unrelated, all three agree. Differences appear only when the groups are unbalanced, which is most real data.
See types of sums of squaresType I, II and III sums of squaresWays to split variance among correlated factors in unbalanced ANOVA; they answer different questions. for how they're computed.
Compare them
ExploreNow ask each main effect after the other, in both languages. Order no longer matters.
anova_lm(smf.ols("mpg ~ am_f + cyl_f", df).fit(), typ=2)
# am_f F = 3.892
# cyl_f F = 24.158drop1(lm(mpg ~ am_f + cyl_f, df), test = "F")
# am_f F = 3.892
# cyl_f F = 24.158R's car::Anova gives the same result with type = 2. Note where the Python and R defaults land: both anova_lm and anova are Type I, so here at least they agree, and it's the default itself that surprises people.
What the app does
In the appFactorial ANOVA in Analyze defaults to Type III with sum-to-zero contrasts, and offers Type II and sequential Type I under one option, so it can't happen silently. The card's text names the type it used.
With an interaction in the model, on this unbalanced data, the card reports the transmission effect as = 3.25.
interaction: F(2, 26) = 1.38, p = .269
- R²
- 0.7877
- Residual df
- 26
Effect size
- Partial η² (am_f) 0.1111
- Partial η² (cyl_f) 0.6319
- Partial η² (am_f × cyl_f) 0.0962
Plots
View data
| CI high | CI low | Mean mpg | cyl_f | am_f |
|---|---|---|---|---|
| 25.886 | 19.914 | 22.900 | 4 | automatic |
| 29.904 | 26.246 | 28.075 | 4 | manual |
| 21.711 | 16.539 | 19.125 | 6 | automatic |
| 23.553 | 17.581 | 20.567 | 6 | manual |
| 16.543 | 13.557 | 15.050 | 8 | automatic |
| 19.057 | 11.743 | 15.400 | 8 | manual |
Assumptions
- Normality of residuals — Shapiro–Wilk on the residuals: p = .326.
- Equal variances across cells — Brown–Forsythe F = 2.74, p = .041 across 6 cells.
- Balanced design — Cell sizes range from 2 to 12; Type 3 sums of squares are used.
ANOVA (Type III sums of squares)
| Source | SS | df | MS | F | p | η²p | ω²p |
|---|---|---|---|---|---|---|---|
| am_f | 29.867 | 1 | 29.867 | 3.248 | .083 | 0.1111 | 0.0656 |
| cyl_f | 410.46 | 2 | 205.23 | 22.321 | < .001 | 0.6319 | 0.5713 |
| am_f × cyl_f | 25.437 | 2 | 12.718 | 1.383 | .269 | 0.0962 | 0.0234 |
| Residual | 239.06 | 26 | 9.195 | — | — | — | — |
Estimated marginal means
| Factor | Level | EMM | SE | CI low | CI high |
|---|---|---|---|---|---|
| am_f | automatic | 19.025 | 0.8253 | 17.617 | 20.433 |
| am_f | manual | 21.347 | 0.9895 | 19.660 | 23.035 |
| cyl_f | 4 | 25.488 | 1.026 | 23.737 | 27.238 |
| cyl_f | 6 | 19.846 | 1.158 | 17.871 | 21.821 |
| cyl_f | 8 | 15.225 | 1.158 | 13.250 | 17.200 |
Pairwise comparisons of marginal means (Bonferroni adjustment)
| Factor | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| am_f | automatic - manual | −2.322 | 1.288 | −1.802 | .083 | −4.520 | −0.1246 |
| cyl_f | 4 - 6 | 5.642 | 1.547 | 3.646 | .004 | 2.164 | 9.119 |
| cyl_f | 4 - 8 | 10.262 | 1.547 | 6.632 | < .001 | 6.785 | 13.740 |
| cyl_f | 6 - 8 | 4.621 | 1.638 | 2.822 | .027 | 0.9407 | 8.301 |
- Model: mpg ~ am_f * cyl_f with sum-to-zero contrasts; marginal means weight the cells equally.
The exact R script · R 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 b33dda13321bb672
# Dataset: mtcars (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/mtcars.parquet", col_select = c("mpg", "am_f", "cyl_f")))
n_input <- nrow(df)
df[["am_f"]] <- factor(df[["am_f"]], levels = c("automatic", "manual")) # stored level order
df[["cyl_f"]] <- factor(df[["cyl_f"]], levels = c("4", "6", "8")) # stored level order
df <- df[stats::complete.cases(df[c("mpg", "am_f", "cyl_f")]), , 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("mpg", "am_f", "cyl_f")) # infinite values stop the run (registry/errors.yaml)
# %% Model
y <- "mpg"
factor_cols <- c("am_f", "cyl_f")
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.9
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 <- "bonferroni"
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"))))
))
interaction: F(2, 26) = 1.38, p = .269
- R²
- 0.7877
- Residual df
- 26
Effect size
- Partial η² (am_f) 0.1111
- Partial η² (cyl_f) 0.6319
- Partial η² (am_f × cyl_f) 0.0962
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of residuals — Shapiro–Wilk on the residuals: p = .326.
- Equal variances across cells — Brown–Forsythe F = 2.74, p = .041 across 6 cells.
- Balanced design — Cell sizes range from 2 to 12; Type 3 sums of squares are used.
ANOVA (Type III sums of squares)
| Source | SS | df | MS | F | p | η²p | ω²p |
|---|---|---|---|---|---|---|---|
| am_f | 29.867 | 1 | 29.867 | 3.248 | .083 | 0.1111 | 0.0656 |
| cyl_f | 410.46 | 2 | 205.23 | 22.321 | < .001 | 0.6319 | 0.5713 |
| am_f × cyl_f | 25.437 | 2 | 12.718 | 1.383 | .269 | 0.0962 | 0.0234 |
| Residual | 239.06 | 26 | 9.195 | — | — | — | — |
Estimated marginal means
| Factor | Level | EMM | SE | CI low | CI high |
|---|---|---|---|---|---|
| am_f | automatic | 19.025 | 0.8253 | 17.617 | 20.433 |
| am_f | manual | 21.347 | 0.9895 | 19.660 | 23.035 |
| cyl_f | 4 | 25.488 | 1.026 | 23.737 | 27.238 |
| cyl_f | 6 | 19.846 | 1.158 | 17.871 | 21.821 |
| cyl_f | 8 | 15.225 | 1.158 | 13.250 | 17.200 |
Pairwise comparisons of marginal means (Bonferroni adjustment)
| Factor | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| am_f | automatic - manual | −2.322 | 1.288 | −1.802 | .083 | −4.520 | −0.1246 |
| cyl_f | 4 - 6 | 5.642 | 1.547 | 3.646 | .004 | 2.164 | 9.119 |
| cyl_f | 4 - 8 | 10.263 | 1.547 | 6.632 | < .001 | 6.785 | 13.740 |
| cyl_f | 6 - 8 | 4.621 | 1.638 | 2.822 | .027 | 0.9407 | 8.301 |
- Model: mpg ~ am_f * cyl_f with sum-to-zero contrasts; marginal means weight the cells equally.
The exact Python script · Python 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 b33dda13321bb672
# Dataset: mtcars (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/mtcars.parquet", columns=["mpg", "am_f", "cyl_f"])
n_input = len(df)
df["am_f"] = pd.Categorical(df["am_f"], categories=["automatic", "manual"]) # stored level order
df["cyl_f"] = pd.Categorical(df["cyl_f"], categories=["4", "6", "8"]) # stored level order
df = df.dropna(subset=["mpg", "am_f", "cyl_f"]) # listwise deletion over the analysis columns
df["am_f"] = df["am_f"].cat.remove_unused_categories()
df["cyl_f"] = df["cyl_f"].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, ["mpg", "am_f", "cyl_f"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
y = "mpg"
factor_cols = ["am_f", "cyl_f"]
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.9
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 = "bonferroni"
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")})],
})
Change the type with Change one thing and watch what moves.
Check your understanding
CheckpointCheck yourself
You call anova(lm(y ~ a + b)) in R on unbalanced data. Which type do you get?
Show the answer
Answer: a
R's anova and statsmodels' anova_lm both default to sequential tests. Reverse the terms and the numbers change.
Check yourself
When do Types I, II and III give the same answer for main effects?
Show the answer
Answer: b
Balance makes the factors orthogonal, so nothing is shared between them and the order of testing can't matter.
Check yourself
What should a results section say when reporting a factorial ANOVA on unbalanced data?
Show the answer
Answer: b
Name it, and choose it before you see the results. Picking the type that gives the smallest p-value is a forking path.
Your own unbalanced data
ReflectDo you have a two-way analysis with unequal group sizes? Which type did it use, and did you choose it? If you can't tell, rerun it with the type named.
Recap
Recapanova()andanova_lm()default to sequential Type I, so order matters on unbalanced data.- Type II tests main effects after each other; Type III tests each term after everything.
- Choose a type before seeing results, and name it when you report.
Concepts in this lesson