A complete investigation, start to finish
Follow one real question from the raw numbers to an honest sentence, using a classic experiment on tooth growth.
What runs in CodeSplash
- Two-sample t-test (Welch / Student, or z test) Verified in Python and R
- Permutation test (two independent groups) Verified in Python and R
- Factorial ANOVA (two or three between factors) Verified in Python and R
You will be able to
- Follow a question from data to a conclusion you can defend
- Tell apart what the data show and what they leave open
- Explain why accounting for another variable can sharpen a comparison
The question
ReadA 1947 study gave 60 guinea pigs vitamin C and measured their odontoblasts, the cells that grow teeth. Each animal received one of three doses, as orange juice (OJ) or as ascorbic acid (VC).
Your question: does the way vitamin C is given change tooth growth?
Write the question down before you look at any number. It decides which comparison counts, and it stops you choosing one after you have seen the results.
Tooth growth in guinea pigsLook at the groups
ReadStart with plain numbers. Mean growth was 20.7 with orange juice and 17.0 with ascorbic acid, a gap of 3.70.
Animals within a group differ by more than that. The standard deviations are 6.61 and 8.27.
So the gap could be a real effect, or the luck of which animals landed in which group. You need to know how large a gap luck alone produces.
Shuffle the labels
ExploreEach shuffle below is one world where the way of giving vitamin C made no difference. Make your guess, then see where the real gap falls among the shuffled ones.
BExplorable · Permutation shuffler
Could a difference this large come from shuffling the labels alone?
Shuffle the labels a thousand times. How often will the shuffled difference be as large as the real one?
Data
Statistic
+30 on the last value of the second group.
Commit your prediction above to see the result
Make your prediction to see the result.
CodeSplash ran the same idea 1,999 times. 130 shuffles gave a gap at least this large, so p = .066: uncommon, not rare.
Put a range on it
ReadAn interval tells you more than a yes or no. The Welch t test gives a 95% confidence intervalConfidence intervalA range of effect values compatible with your data at the chosen confidence level. for the gap, from −0.17 to 7.57.
Read it as the range of true gaps the data are compatible with: from a very small disadvantage for orange juice to a sizeable advantage.
t(55.31) = 1.92, p = .061, g = 0.49, 95% CI [−0.02, 0.99]
- t
- 1.915
- df
- 55.309
- p
- .061
- Mean difference (OJ − VC)
- 3.700
- 95% CI
- [−0.1710, 7.571]
Effect size
- Hedges' g 0.4881 95% CI [−0.0212, 0.9933] · small
- Cohen's d 0.4945 95% CI [−0.0215, 1.006] · small
Plots
View data
| supp | len |
|---|---|
| VC | 4.200 |
| VC | 11.500 |
| VC | 7.300 |
| VC | 5.800 |
| VC | 6.400 |
| VC | 10 |
| VC | 11.200 |
| VC | 11.200 |
| VC | 5.200 |
| VC | 7 |
| VC | 16.500 |
| VC | 16.500 |
| VC | 15.200 |
| VC | 17.300 |
| VC | 22.500 |
| VC | 17.300 |
| VC | 13.600 |
| VC | 14.500 |
| VC | 18.800 |
| VC | 15.500 |
| VC | 23.600 |
| VC | 18.500 |
| VC | 33.900 |
| VC | 25.500 |
| VC | 26.400 |
| VC | 32.500 |
| VC | 26.700 |
| VC | 21.500 |
| VC | 23.300 |
| VC | 29.500 |
| OJ | 15.200 |
| OJ | 21.500 |
| OJ | 17.600 |
| OJ | 9.700 |
| OJ | 14.500 |
| OJ | 10 |
| OJ | 8.200 |
| OJ | 9.400 |
| OJ | 16.500 |
| OJ | 9.700 |
| OJ | 19.700 |
| OJ | 23.300 |
| OJ | 23.600 |
| OJ | 26.400 |
| OJ | 20 |
| OJ | 25.200 |
| OJ | 25.800 |
| OJ | 21.200 |
| OJ | 14.500 |
| OJ | 27.300 |
| OJ | 25.500 |
| OJ | 26.400 |
| OJ | 22.400 |
| OJ | 24.500 |
| OJ | 24.800 |
| OJ | 30.900 |
| OJ | 26.400 |
| OJ | 27.300 |
| OJ | 29.400 |
| OJ | 23 |
Assumptions
- Normality within groups — Shapiro–Wilk p < .05 in OJ, but each group has at least 30 values, so the t-test is robust.
- Equal variances — Welch's test does not assume equal variances (Brown–Forsythe F = 1.21, p = .275).
Descriptives
| supp | n | Mean | SD | SE | Median | Min | Max |
|---|---|---|---|---|---|---|---|
| OJ | 30 | 20.663 | 6.606 | 1.206 | 22.700 | 8.200 | 30.900 |
| VC | 30 | 16.963 | 8.266 | 1.509 | 16.500 | 4.200 | 33.900 |
- Difference = OJ − VC; alternative: two-sided; H0 difference = 0.
The exact R script · R R version 4.5.1 (2025-06-13)
# Two-sample t-test (Welch / Student, or z test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.independent 1.2.3 · spec 13475d40a03ae331
# Dataset: toothgrowth (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/toothgrowth.parquet", col_select = c("len", "supp")))
n_input <- nrow(df)
df[["supp"]] <- factor(df[["supp"]], levels = c("OJ", "VC")) # stored level order
df <- df[stats::complete.cases(df[c("len", "supp")]), , 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("len", "supp")) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro-Wilk keeps the
# method's own row; any other choice replaces it (cs_normality_test; a simulated p such as
# Filliben's uses the fixed seed 42, so Python draws the same stream).
normality_test <- "shapiro_wilk"
normality_selected <- function(samples, row_label, small) {
res <- lapply(samples, function(s) cs_normality_test(as.numeric(s), normality_test, 42, 1999))
ok <- Filter(function(r) is.finite(r$p), res)
label <- res[[1]]$label
symbol <- res[[1]]$symbol
if (!length(ok)) {
return(list(row = list(key = "normality", label = row_label, status = "info",
detail = sprintf("%s is not available for these sample sizes.", label)), p = NULL))
}
ps <- vapply(ok, function(r) r$p, 0)
p_min <- min(ps)
bad <- sum(ps < 0.05)
status <- if (bad) (if (small) "warn" else "info") else "pass"
tail <- if (status == "warn") "; consider a rank-based or robust method." else "."
row <- if (length(samples) == 1) {
list(key = "normality", label = row_label, status = status, statistic = ok[[1]]$statistic, p = ok[[1]]$p,
detail = paste0(sprintf("%s %s = %.3f, %s", label, symbol, ok[[1]]$statistic, cs_fmt_p(ok[[1]]$p)), tail))
} else {
list(key = "normality", label = row_label, status = status,
detail = paste0(if (bad) sprintf("%s: p < .05 in %d of %d groups (smallest %s)", label, bad, length(ok), cs_fmt_p(p_min))
else sprintf("%s: p ≥ .05 in every group", label), tail))
}
list(row = row, p = p_min)
}
# %% Helpers
ncp_ci <- function(t, df, conf) {
# CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)
solve <- function(prob) {
# P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
f <- function(ncp) suppressWarnings(pt(t, df, ncp)) - prob
lo <- t - 1
hi <- t + 1
step <- 1
while (f(lo) < 0) {
lo <- lo - step
step <- step * 2
}
step <- 1
while (f(hi) > 0) {
hi <- hi + step
step <- step * 2
}
uniroot(f, c(lo, hi), tol = 1e-12)$root
}
alpha <- 1 - conf
c(solve(1 - alpha / 2), solve(alpha / 2))
}
hedges_j <- function(df) {
# Exact small-sample correction J = gamma(df/2) / (sqrt(df/2) * gamma((df - 1)/2))
exp(lgamma(df / 2) - log(sqrt(df / 2)) - lgamma((df - 1) / 2))
}
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
y <- "len"
g <- "supp"
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
levels_g <- levels(df[[g]])
if (length(levels_g) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(levels_g))
x1 <- df[[y]][df[[g]] == levels_g[1]]
x2 <- df[[y]][df[[g]] == levels_g[2]]
n1 <- length(x1)
n2 <- length(x2)
alternative <- "two-sided"
conf <- 0.95
mu <- 0 # hypothesized difference (first - second)
equal_var <- FALSE # pinned: FALSE = Welch
sigma_1 <- NULL # known population SDs: z test (guide entry 007); NULL = t test
sigma_2 <- NULL # NULL = the same as the first group's
if (any(is.infinite(df[[y]]))) cs_error("CS_E_NOT_FINITE", column = y, count = sum(is.infinite(df[[y]])))
if (is.null(sigma_1)) { # the t test needs two values per group and some variation
for (i in 1:2) {
if (c(n1, n2)[i] < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = paste0(g, " = ", levels_g[i]), n = c(n1, n2)[i])
}
if (length(unique(df[[y]])) < 2) cs_error("CS_E_CONSTANT", column = y)
}
m1 <- mean(x1)
m2 <- mean(x2)
s1 <- sd(x1)
s2 <- sd(x2)
diff <- m1 - m2
if (is.null(sigma_1)) {
res <- t.test(x1, x2, alternative = sub("-", ".", alternative, fixed = TRUE), mu = mu,
var.equal = equal_var, conf.level = conf)
t <- unname(res$statistic)
dof <- unname(res$parameter)
p <- res$p.value
z_stat <- NULL
ci_low <- res$conf.int[1]
ci_high <- res$conf.int[2]
se_diff <- if (!equal_var) sqrt(s1^2 / n1 + s2^2 / n2) else NULL
} else {
zr <- cs_z_two(x1, x2, sigma_1, sigma_2, mu, conf, alternative) # z with known SDs, normal reference
t <- NULL
dof <- NULL
p <- zr$p
z_stat <- zr$z
ci_low <- zr$ci_low
ci_high <- zr$ci_high
se_diff <- zr$se
}
# Effect size: Cohen's d with the pooled SD, Hedges' g with the exact J, noncentral-t CI.
df_pooled <- n1 + n2 - 2
sp <- sqrt(((n1 - 1) * s1^2 + (n2 - 1) * s2^2) / df_pooled)
d <- diff / sp
scale <- sqrt(1 / n1 + 1 / n2)
nc <- ncp_ci(d / scale, df_pooled, conf)
j <- hedges_j(df_pooled)
g_est <- d * j
g_low <- nc[1] * scale * j
g_high <- nc[2] * scale * j
# %% Assumptions
assumptions <- list()
sw <- lapply(list(x1, x2), function(x) if (length(x) >= 3 && length(x) <= 5000) shapiro.test(x) else NULL)
names(sw) <- levels_g
sw_p <- vapply(sw, function(s) if (is.null(s)) NA_real_ else s$p.value, numeric(1))
bad <- levels_g[!is.na(sw_p) & sw_p < 0.05]
small <- min(n1, n2) < 30
if (anyNA(sw_p)) {
status <- "info"
detail <- "Too few (or too many) values in a group for Shapiro–Wilk; inspect the distributions."
} else if (length(bad) && small) {
status <- "warn"
detail <- sprintf("Shapiro–Wilk p < .05 in %s with fewer than 30 values; consider Mann–Whitney or a bootstrap CI.", paste(bad, collapse = ", "))
} else if (length(bad)) {
status <- "info"
detail <- sprintf("Shapiro–Wilk p < .05 in %s, but each group has at least 30 values, so the t-test is robust.", paste(bad, collapse = ", "))
} else {
status <- "pass"
detail <- "Shapiro–Wilk p ≥ .05 in both groups."
}
assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Normality within groups", status = status, detail = detail)
# Brown-Forsythe (median-centered Levene): one-way ANOVA on |x - group median|
z <- c(abs(x1 - median(x1)), abs(x2 - median(x2)))
gz <- factor(rep(levels_g, c(n1, n2)), levels = levels_g)
lev <- oneway.test(z ~ gz, var.equal = TRUE)
lev_f <- unname(lev$statistic)
lev_p <- lev$p.value
if (equal_var) {
status <- if (lev_p < 0.05) "warn" else "pass"
detail <- paste0(sprintf("Brown–Forsythe F = %.2f, %s", lev_f, cs_fmt_p(lev_p)),
if (lev_p < 0.05) "; Welch's test is safer." else ".")
} else {
status <- "info"
detail <- sprintf("Welch's test does not assume equal variances (Brown–Forsythe F = %.2f, %s).", lev_f, cs_fmt_p(lev_p))
}
assumptions[[length(assumptions) + 1]] <- list(key = "equal_variance", label = "Equal variances", status = status,
detail = detail, statistic = lev_f, p = lev_p)
# Equal-variance row: the dialog's `variance_test` (Brown-Forsythe above is the default).
variance_test <- "brown_forsythe"
if (variance_test != "brown_forsythe") {
vt <- cs_spread_test(c(x1, x2), rep(0:1, c(n1, n2)), variance_test) # cs_spread_test <-> codesplash.stats.spread
lev_f <- vt$statistic
lev_p <- vt$p
shown <- sprintf("%s %s = %.2f, %s", vt$label, vt$symbol, lev_f, cs_fmt_p(lev_p))
if (!equal_var) {
status <- "info"
detail <- sprintf("Welch's test does not assume equal variances (%s).", shown)
} else {
status <- if (lev_p < 0.05) "warn" else "pass"
detail <- paste0(shown, if (lev_p < 0.05) "; Welch's test is safer." else ".")
}
assumptions <- lapply(assumptions, function(a) if (a$key == "equal_variance") list(key = "equal_variance", label = "Equal variances",
status = status, detail = detail, statistic = lev_f, p = lev_p) else a)
}
if (min(n1, n2) < 5) {
assumptions[[length(assumptions) + 1]] <- list(key = "sample_size", label = "Sample size", status = "warn",
detail = "A group has fewer than 5 values; estimates are unstable.")
warnings <- c(warnings, "A group has fewer than 5 values.")
}
normality_p <- NULL
if (normality_test != "shapiro_wilk") {
ns_ <- normality_selected(list(x1, x2), "Normality within groups", min(n1, n2) < 30)
normality_p <- ns_$p
assumptions <- lapply(assumptions, function(a) if (a$key == "normality") ns_$row else a)
}
# %% Result
alpha <- 1 - conf
if (is.null(se_diff)) se_diff <- sp * scale # Student's pooled standard error
# Lens (equivalence / minimal effect / non-inferiority) on the difference, at alpha = 1 - confidence.
lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") lens <- cs_lens(lens_kind, diff, se_diff, dof, NULL, NULL, 1 - conf)
name <- if (equal_var) "Student's" else "Welch's"
df_text <- if (is.null(dof)) NULL else if (equal_var) sprintf("%.0f", dof) else sprintf("%.2f", dof)
lead <- if (!is.null(z_stat)) sprintf("z = %s", cs_fmt_num(z_stat)) else sprintf("t(%s) = %s", df_text, cs_fmt_num(t))
pct <- sprintf("%.0f%%", conf * 100)
significance <- if (p < alpha) {
sprintf("The difference is statistically significant (%s).", cs_fmt_p(p))
} else {
sprintf("The data are compatible with no difference (%s).", cs_fmt_p(p))
}
size <- magnitude(g_est, c(0.2, 0.5, 0.8))
summary <- sprintf(
"Mean %s was %s in %s (%.2f) than in %s (%.2f): a difference of %.2f, %s CI [%.2f, %.2f]. %s The standardized difference is %s (g = %.2f).",
y, if (diff > 0) "higher" else "lower", levels_g[1], m1, levels_g[2], m2, diff, pct, ci_low, ci_high, significance, size, g_est
)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s): %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
values <- list(
t = t, df = dof, p = p, z = z_stat, mean_diff = diff, ci_low = ci_low, ci_high = ci_high,
mean_1 = m1, mean_2 = m2, sd_1 = s1, sd_2 = s2, n_1 = n1, n_2 = n2,
cohens_d = d, hedges_g = g_est, g_ci_low = g_low, g_ci_high = g_high,
levene_f = lev_f, levene_p = lev_p,
sw_p_1 = if (is.na(sw_p[[1]])) NULL else sw_p[[1]],
sw_p_2 = if (is.na(sw_p[[2]])) NULL else sw_p[[2]],
level_1 = as.character(levels_g[1]), level_2 = as.character(levels_g[2])
)
if (!is.null(lens)) values <- c(values, lens)
if (!is.null(normality_p)) values$normality_p <- normality_p
descriptives <- do.call(rbind, lapply(seq_along(levels_g), function(i) {
x <- list(x1, x2)[[i]]
data.frame(group = levels_g[i], n = length(x), mean = mean(x), sd = sd(x), se = sd(x) / sqrt(length(x)),
median = unname(quantile(x, 0.5, type = 7)), min = min(x), max = max(x))
}))
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
method = "ttest.independent",
methodVersion = "1.2.3",
title = if (!is.null(z_stat)) "Two-sample z-test" else paste(name, "two-sample t-test"),
engine = cs_engine_info("stats", "nanoparquet"),
n = n1 + n2,
summary = summary,
apa = sprintf("%s, %s, g = %s, %s CI [%s, %s]", lead, cs_fmt_p(p), cs_fmt_num(g_est), pct,
cs_fmt_num(g_low), cs_fmt_num(g_high)),
statistics = c(
if (!is.null(z_stat)) list(list(key = "z", label = "z", value = z_stat))
else list(list(key = "t", label = "t", value = t), list(key = "df", label = "df", value = dof)),
list(
list(key = "p", label = "p", value = p, format = "p"),
list(key = "mean_diff", label = sprintf("Mean difference (%s − %s)", levels_g[1], levels_g[2]), value = diff),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high))
),
if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list()
),
tables = list(list(
key = "descriptives", title = "Descriptives",
columns = list(
list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "median", label = "Median", type = "number"),
list(key = "min", label = "Min", type = "number"), list(key = "max", label = "Max", type = "number")
),
rows = descriptives
)),
effectSizes = list(
list(key = "hedges_g", label = "Hedges' g", value = g_est, ciLow = g_low, ciHigh = g_high, ciLevel = conf,
method = "pooled SD, exact J, noncentral-t interval", magnitude = size, ruleSet = "Cohen (1988)"),
list(key = "cohens_d", label = "Cohen's d", value = d, ciLow = nc[1] * scale, ciHigh = nc[2] * scale, ciLevel = conf,
method = "pooled SD, noncentral-t interval", magnitude = magnitude(d, c(0.2, 0.5, 0.8)), ruleSet = "Cohen (1988)")
),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("Difference = %s − %s; alternative: %s; H0 difference = %s.", levels_g[1], levels_g[2], alternative, format(mu))),
if (!is.null(z_stat)) list(sprintf("z test with known population SDs σ₁ = %s, σ₂ = %s.", format(sigma_1), format(if (is.null(sigma_2)) sigma_1 else sigma_2))) else list(),
if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the %.0f%% interval for the difference.", lens$lens_ci_low, lens$lens_ci_high, (1 - 2 * (1 - conf)) * 100)) else list()),
values = values,
charts = list(cs_chart(
"distribution", "raincloud", sprintf("%s by %s", y, g),
# at most 5,000 evenly spaced rows: a picture, not a statistic
list(y = cs_col(y, df[[y]][chart_rows]), group = cs_col(g, as.character(df[[g]][chart_rows]), levels = levels_g))
))
))
t(55.31) = 1.92, p = .061, g = 0.49, 95% CI [−0.02, 0.99]
- t
- 1.915
- df
- 55.309
- p
- .061
- Mean difference (OJ − VC)
- 3.700
- 95% CI
- [−0.1710, 7.571]
Effect size
- Hedges' g 0.4881 95% CI [−0.0212, 0.9933] · small
- Cohen's d 0.4945 95% CI [−0.0215, 1.006] · small
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality within groups — Shapiro–Wilk p < .05 in OJ, but each group has at least 30 values, so the t-test is robust.
- Equal variances — Welch's test does not assume equal variances (Brown–Forsythe F = 1.21, p = .275).
Descriptives
| supp | n | Mean | SD | SE | Median | Min | Max |
|---|---|---|---|---|---|---|---|
| OJ | 30 | 20.663 | 6.606 | 1.206 | 22.700 | 8.200 | 30.900 |
| VC | 30 | 16.963 | 8.266 | 1.509 | 16.500 | 4.200 | 33.900 |
- Difference = OJ − VC; alternative: two-sided; H0 difference = 0.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Two-sample t-test (Welch / Student, or z test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.independent 1.2.3 · spec 13475d40a03ae331
# Dataset: toothgrowth (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 optimize, special, stats
import codesplash as cs
from codesplash.stats import means as csm
# %% Data
df = pd.read_parquet("tests/parity/fixtures/toothgrowth.parquet", columns=["len", "supp"])
n_input = len(df)
df["supp"] = pd.Categorical(df["supp"], categories=["OJ", "VC"]) # stored level order
df = df.dropna(subset=["len", "supp"]) # listwise deletion over the analysis columns
df["supp"] = df["supp"].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, ["len", "supp"]) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro–Wilk keeps the
# method's own row; any other choice replaces it (codesplash.stats.normality.normality_test; a
# simulated p such as Filliben's uses the fixed seed 42, so R draws the same stream).
normality_test = "shapiro_wilk"
def normality_selected(samples, row_label, small):
from codesplash.stats import normality as csn
res = [csn.normality_test(np.asarray(s, dtype=float), normality_test, 42, 1999) for s in samples]
ok = [r for r in res if np.isfinite(r["p"])]
label, symbol = res[0]["label"], res[0]["symbol"]
if not ok:
return {"key": "normality", "label": row_label, "status": "info", "detail": f"{label} is not available for these sample sizes."}, None
p_min = min(r["p"] for r in ok)
bad = sum(r["p"] < 0.05 for r in ok)
status = ("warn" if small else "info") if bad else "pass"
row = {"key": "normality", "label": row_label, "status": status}
if len(samples) == 1:
row.update({"statistic": ok[0]["statistic"], "p": ok[0]["p"],
"detail": f"{label} {symbol} = {ok[0]['statistic']:.3f}, {cs.fmt_p(ok[0]['p'])}" + ("; consider a rank-based or robust method." if status == "warn" else ".")})
else:
row["detail"] = (f"{label}: p < .05 in {bad} of {len(ok)} groups (smallest {cs.fmt_p(p_min)})" if bad
else f"{label}: p ≥ .05 in every group") + ("; consider a rank-based or robust method." if status == "warn" else ".")
return row, p_min
# %% Helpers
def ncp_ci(t, df, conf):
"""CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)."""
def solve(prob):
# P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
f = lambda ncp: stats.nct.cdf(t, df, ncp) - prob # noqa: E731
lo, hi, step = t - 1.0, t + 1.0, 1.0
while f(lo) < 0:
lo, step = lo - step, step * 2
step = 1.0
while f(hi) > 0:
hi, step = hi + step, step * 2
return optimize.brentq(f, lo, hi, xtol=1e-12)
alpha = 1 - conf
return solve(1 - alpha / 2), solve(alpha / 2)
def hedges_j(df):
"""Exact small-sample correction J = Γ(df/2) / (√(df/2) · Γ((df − 1)/2))."""
return float(np.exp(special.gammaln(df / 2) - np.log(np.sqrt(df / 2)) - special.gammaln((df - 1) / 2)))
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
y, g = "len", "supp"
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
levels = list(df[g].cat.categories)
if len(levels) != 2:
cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
x1 = df.loc[df[g] == levels[0], y].to_numpy(dtype=float)
x2 = df.loc[df[g] == levels[1], y].to_numpy(dtype=float)
n1, n2 = len(x1), len(x2)
alternative = "two-sided"
conf = 0.95
mu = 0 # hypothesized difference (first − second)
equal_var = False # pinned: False = Welch (R's default; scipy's default is Student)
sigma_1 = None # known population SDs: z test (guide entry 007); None = t test
sigma_2 = None # None = the same as the first group's
if np.isinf(df[y].to_numpy(dtype=float)).any():
cs.cs_error("CS_E_NOT_FINITE", column=y, count=int(np.isinf(df[y].to_numpy(dtype=float)).sum()))
if sigma_1 is None: # the t test needs two values per group and some variation
for lvl, n_g in zip(levels, (n1, n2)):
if n_g < 2:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=f"{g} = {lvl}", n=n_g)
if df[y].nunique() < 2:
cs.cs_error("CS_E_CONSTANT", column=y)
m1, m2 = x1.mean(), x2.mean()
s1, s2 = x1.std(ddof=1), x2.std(ddof=1)
diff = m1 - m2
if sigma_1 is None:
# scipy tests mean(x1) − mean(x2) = 0, so shift x1 by mu and shift the interval back.
res = stats.ttest_ind(x1 - mu, x2, equal_var=equal_var, alternative=alternative)
ci = res.confidence_interval(confidence_level=conf)
t, dof, p, z = float(res.statistic), float(res.df), float(res.pvalue), None
ci_low, ci_high = float(ci.low) + mu, float(ci.high) + mu
se_diff = float(np.sqrt(s1**2 / n1 + s2**2 / n2)) if not equal_var else None
else:
zr = csm.z_two(x1, x2, sigma_1, sigma_2, mu, conf, alternative) # z with known SDs, normal reference
t, dof, p, z = None, None, zr["p"], zr["z"]
ci_low, ci_high = zr["ci_low"], zr["ci_high"]
se_diff = zr["se"]
# Effect size: Cohen's d with the pooled SD, Hedges' g with the exact J, noncentral-t CI.
df_pooled = n1 + n2 - 2
sp = np.sqrt(((n1 - 1) * s1**2 + (n2 - 1) * s2**2) / df_pooled)
d = diff / sp
scale = np.sqrt(1 / n1 + 1 / n2)
nc_low, nc_high = ncp_ci(d / scale, df_pooled, conf)
j = hedges_j(df_pooled)
g_est, g_low, g_high = d * j, nc_low * scale * j, nc_high * scale * j
if se_diff is None:
se_diff = float(sp * scale) # Student's pooled standard error
# Lens (equivalence / minimal effect / non-inferiority) on the difference, at α = 1 − confidence.
lens_kind = "none"
lens = None
if lens_kind != "none":
lens = csm.lens(lens_kind, diff, se_diff, dof, None, None, 1 - conf)
# %% Assumptions
assumptions = []
sw = {}
for level, x in zip(levels, (x1, x2)):
sw[level] = stats.shapiro(x) if 3 <= len(x) <= 5000 else None
bad = [lv for lv in levels if sw[lv] is not None and sw[lv].pvalue < 0.05]
small = min(n1, n2) < 30
if any(sw[lv] is None for lv in levels):
status, detail = "info", "Too few (or too many) values in a group for Shapiro–Wilk; inspect the distributions."
elif bad and small:
status, detail = "warn", f"Shapiro–Wilk p < .05 in {', '.join(map(str, bad))} with fewer than 30 values; consider Mann–Whitney or a bootstrap CI."
elif bad:
status, detail = "info", f"Shapiro–Wilk p < .05 in {', '.join(map(str, bad))}, but each group has at least 30 values, so the t-test is robust."
else:
status, detail = "pass", "Shapiro–Wilk p ≥ .05 in both groups."
assumptions.append({"key": "normality", "label": "Normality within groups", "status": status, "detail": detail})
lev = stats.levene(x1, x2, center="median") # Brown–Forsythe (median-centered Levene)
if equal_var:
status = "warn" if lev.pvalue < 0.05 else "pass"
detail = f"Brown–Forsythe F = {lev.statistic:.2f}, {cs.fmt_p(lev.pvalue)}" + ("; Welch's test is safer." if lev.pvalue < 0.05 else ".")
else:
status = "info"
detail = f"Welch's test does not assume equal variances (Brown–Forsythe F = {lev.statistic:.2f}, {cs.fmt_p(lev.pvalue)})."
assumptions.append({"key": "equal_variance", "label": "Equal variances", "status": status, "detail": detail, "statistic": float(lev.statistic), "p": float(lev.pvalue)})
# Equal-variance row: the dialog's `variance_test` (Brown–Forsythe above is the default).
variance_test = "brown_forsythe"
lev_f, lev_p = float(lev.statistic), float(lev.pvalue)
if variance_test != "brown_forsythe":
from codesplash.stats import spread
vt = spread.spread_test(np.concatenate([x1, x2]), np.repeat([0, 1], [n1, n2]), variance_test) # codesplash.stats.spread ↔ cs_spread_test
lev_f, lev_p = float(vt["statistic"]), float(vt["p"])
shown = f"{vt['label']} {vt['symbol']} = {lev_f:.2f}, {cs.fmt_p(lev_p)}"
if not equal_var:
status, detail = "info", f"Welch's test does not assume equal variances ({shown})."
else:
status = "warn" if lev_p < 0.05 else "pass"
detail = shown + ("; " + "Welch's test" + " is safer." if lev_p < 0.05 else ".")
assumptions = [{"key": "equal_variance", "label": "Equal variances", "status": status, "detail": detail, "statistic": lev_f, "p": lev_p}
if a["key"] == "equal_variance" else a for a in assumptions]
if min(n1, n2) < 5:
assumptions.append({"key": "sample_size", "label": "Sample size", "status": "warn", "detail": "A group has fewer than 5 values; estimates are unstable."})
warnings.append("A group has fewer than 5 values.")
normality_p = None
if normality_test != "shapiro_wilk":
_row, normality_p = normality_selected([x1, x2], "Normality within groups", min(n1, n2) < 30)
assumptions = [_row if a["key"] == "normality" else a for a in assumptions]
# %% Result
alpha = 1 - conf
name = "Student's" if equal_var else "Welch's"
lead = f"z = {cs.fmt_num(z)}" if z is not None else None
df_text = None if dof is None else (f"{dof:.0f}" if equal_var else f"{dof:.2f}")
if lead is None:
lead = f"t({df_text}) = {cs.fmt_num(t)}"
direction = "higher" if diff > 0 else "lower"
significance = (
f"The difference is statistically significant ({cs.fmt_p(p)})."
if p < alpha
else f"The data are compatible with no difference ({cs.fmt_p(p)})."
)
size = magnitude(g_est, (0.2, 0.5, 0.8))
summary = (
f"Mean {y} was {direction} in {levels[0]} ({m1:.2f}) than in {levels[1]} ({m2:.2f}): a difference of "
f"{diff:.2f}, {conf:.0%} CI [{ci_low:.2f}, {ci_high:.2f}]. {significance} The standardized difference is {size} (g = {g_est:.2f})."
)
if lens:
summary += f" Lens ({lens_kind.replace('_', ' ')}): {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
descriptives = [
{"group": str(lv), "n": len(x), "mean": float(x.mean()), "sd": float(x.std(ddof=1)), "se": float(x.std(ddof=1) / np.sqrt(len(x))),
"median": float(np.quantile(x, 0.5)), "min": float(x.min()), "max": float(x.max())}
for lv, x in zip(levels, (x1, x2))
]
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
"method": "ttest.independent",
"methodVersion": "1.2.3",
"title": "Two-sample z-test" if z is not None else f"{name} two-sample t-test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n1 + n2,
"summary": summary,
"apa": f"{lead}, {cs.fmt_p(p)}, g = {cs.fmt_num(g_est)}, {conf:.0%} CI [{cs.fmt_num(g_low)}, {cs.fmt_num(g_high)}]",
"statistics": ([{"key": "z", "label": "z", "value": z}] if z is not None else
[{"key": "t", "label": "t", "value": t}, {"key": "df", "label": "df", "value": dof}]) + [
{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "mean_diff", "label": f"Mean difference ({levels[0]} − {levels[1]})", "value": diff},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else []),
"tables": [{
"key": "descriptives", "title": "Descriptives",
"columns": [
{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "median", "label": "Median", "type": "number"},
{"key": "min", "label": "Min", "type": "number"}, {"key": "max", "label": "Max", "type": "number"},
],
"rows": descriptives,
}],
"effectSizes": [
{"key": "hedges_g", "label": "Hedges' g", "value": g_est, "ciLow": g_low, "ciHigh": g_high, "ciLevel": conf,
"method": "pooled SD, exact J, noncentral-t interval", "magnitude": size, "ruleSet": "Cohen (1988)"},
{"key": "cohens_d", "label": "Cohen's d", "value": d, "ciLow": nc_low * scale, "ciHigh": nc_high * scale, "ciLevel": conf,
"method": "pooled SD, noncentral-t interval", "magnitude": magnitude(d, (0.2, 0.5, 0.8)), "ruleSet": "Cohen (1988)"},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Difference = {levels[0]} − {levels[1]}; alternative: {alternative}; H0 difference = {mu}."]
+ ([f"z test with known population SDs σ₁ = {sigma_1:g}, σ₂ = {(sigma_2 if sigma_2 is not None else sigma_1):g}."] if z is not None else [])
+ ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the {1 - 2 * (1 - conf):.0%} interval for the difference."] if lens else []),
"values": {
"t": t, "df": dof, "p": p, "z": z, "mean_diff": diff, "ci_low": ci_low, "ci_high": ci_high,
"mean_1": m1, "mean_2": m2, "sd_1": s1, "sd_2": s2, "n_1": n1, "n_2": n2,
"cohens_d": d, "hedges_g": g_est, "g_ci_low": g_low, "g_ci_high": g_high,
"levene_f": lev_f, "levene_p": lev_p,
"sw_p_1": None if sw[levels[0]] is None else float(sw[levels[0]].pvalue),
"sw_p_2": None if sw[levels[1]] is None else float(sw[levels[1]].pvalue),
"level_1": str(levels[0]), "level_2": str(levels[1]),
**(lens or {}),
**({"normality_p": normality_p} if normality_p is not None else {}),
},
"charts": [cs.chart(
"distribution", "raincloud", f"{y} by {g}",
# at most 5,000 evenly spaced rows: a picture, not a statistic
{"y": cs.col(y, df[y].to_numpy(dtype=float)[chart_rows]),
"group": cs.col(g, df[g].astype(str).to_numpy()[chart_rows], levels=[str(x) for x in levels])},
)],
})
Bring dose back in
PredictPredict first
So far you have ignored dose. Doses differ a lot, and those differences sit inside the noise of your comparison. If you account for dose, what happens to the evidence about route?
Reveal
More certain. In a two-way ANOVA the route effect gives F(1, 54) = 15.6, p < .001.
There is also an interactionInteractionWhen the effect of one predictor depends on the level of another., p = .022: orange juice leads at low doses and the gap closes at the top dose.
interaction: F(2, 54) = 4.11, p = .022
- R²
- 0.7937
- Residual df
- 54
Effect size
- Partial η² (supp) 0.2238
- Partial η² (dose_f) 0.7731
- Partial η² (supp × dose_f) 0.1320
Plots
View data
| CI high | CI low | Mean len | dose_f | supp |
|---|---|---|---|---|
| 15.532 | 10.928 | 13.230 | 0.5 | OJ |
| 10.282 | 5.678 | 7.980 | 0.5 | VC |
| 25.002 | 20.398 | 22.700 | 1 | OJ |
| 19.072 | 14.468 | 16.770 | 1 | VC |
| 28.362 | 23.758 | 26.060 | 2 | OJ |
| 28.442 | 23.838 | 26.140 | 2 | VC |
Assumptions
- Normality of residuals — Shapiro–Wilk on the residuals: p = .669.
- Equal variances across cells — Brown–Forsythe F = 1.71, p = .148 across 6 cells.
- Balanced design — 6 cells with 10 observations each.
ANOVA (Type II sums of squares)
| Source | SS | df | MS | F | p | η²p | ω²p |
|---|---|---|---|---|---|---|---|
| supp | 205.35 | 1 | 205.35 | 15.572 | < .001 | 0.2238 | 0.1954 |
| dose_f | 2426.43 | 2 | 1213.22 | 92.000 | < .001 | 0.7731 | 0.7521 |
| supp × dose_f | 108.32 | 2 | 54.160 | 4.107 | .022 | 0.1320 | 0.0938 |
| Residual | 712.11 | 54 | 13.187 | — | — | — | — |
Estimated marginal means
| Factor | Level | EMM | SE | CI low | CI high |
|---|---|---|---|---|---|
| supp | OJ | 20.663 | 0.6630 | 19.334 | 21.993 |
| supp | VC | 16.963 | 0.6630 | 15.634 | 18.293 |
| dose_f | 0.5 | 10.605 | 0.8120 | 8.977 | 12.233 |
| dose_f | 1 | 19.735 | 0.8120 | 18.107 | 21.363 |
| dose_f | 2 | 26.100 | 0.8120 | 24.472 | 27.728 |
Pairwise comparisons of marginal means (Holm adjustment)
| Factor | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| supp | OJ - VC | 3.700 | 0.9376 | 3.946 | < .001 | 1.820 | 5.580 |
| dose_f | 0.5 - 1 | −9.130 | 1.148 | −7.951 | < .001 | −11.432 | −6.828 |
| dose_f | 0.5 - 2 | −15.495 | 1.148 | −13.493 | < .001 | −17.797 | −13.193 |
| dose_f | 1 - 2 | −6.365 | 1.148 | −5.543 | < .001 | −8.667 | −4.063 |
Simple effects of supp within dose_f
| Effect | F | df1 | df2 | p |
|---|---|---|---|---|
| supp | dose_f=0.5 | 10.451 | 1 | 54 | .002 |
| supp | dose_f=1 | 13.333 | 1 | 54 | < .001 |
| supp | dose_f=2 | 0.0024 | 1 | 54 | .961 |
Pairwise comparisons of supp within dose_f
| Within | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| dose_f=0.5 | OJ - VC | 5.250 | 1.624 | 3.233 | .002 | 1.994 | 8.506 |
| dose_f=1 | OJ - VC | 5.930 | 1.624 | 3.651 | < .001 | 2.674 | 9.186 |
| dose_f=2 | OJ - VC | −0.0800 | 1.624 | −0.0493 | .961 | −3.336 | 3.176 |
- Model: len ~ supp * dose_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 1dc19eb9e06d66ca
# Dataset: toothgrowth (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/toothgrowth.parquet", col_select = c("len", "supp", "dose_f")))
n_input <- nrow(df)
df[["supp"]] <- factor(df[["supp"]], levels = c("OJ", "VC")) # stored level order
df[["dose_f"]] <- factor(df[["dose_f"]], levels = c("0.5", "1", "2")) # stored level order
df <- df[stats::complete.cases(df[c("len", "supp", "dose_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("len", "supp", "dose_f")) # infinite values stop the run (registry/errors.yaml)
# %% Model
y <- "len"
factor_cols <- c("supp", "dose_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 <- "2"
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 <- "holm"
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 <- "always"
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, 54) = 4.11, p = .022
- R²
- 0.7937
- Residual df
- 54
Effect size
- Partial η² (supp) 0.2238
- Partial η² (dose_f) 0.7731
- Partial η² (supp × dose_f) 0.1320
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of residuals — Shapiro–Wilk on the residuals: p = .669.
- Equal variances across cells — Brown–Forsythe F = 1.71, p = .148 across 6 cells.
- Balanced design — 6 cells with 10 observations each.
ANOVA (Type II sums of squares)
| Source | SS | df | MS | F | p | η²p | ω²p |
|---|---|---|---|---|---|---|---|
| supp | 205.35 | 1 | 205.35 | 15.572 | < .001 | 0.2238 | 0.1954 |
| dose_f | 2426.43 | 2 | 1213.22 | 92.000 | < .001 | 0.7731 | 0.7521 |
| supp × dose_f | 108.32 | 2 | 54.160 | 4.107 | .022 | 0.1320 | 0.0938 |
| Residual | 712.11 | 54 | 13.187 | — | — | — | — |
Estimated marginal means
| Factor | Level | EMM | SE | CI low | CI high |
|---|---|---|---|---|---|
| supp | OJ | 20.663 | 0.6630 | 19.334 | 21.993 |
| supp | VC | 16.963 | 0.6630 | 15.634 | 18.293 |
| dose_f | 0.5 | 10.605 | 0.8120 | 8.977 | 12.233 |
| dose_f | 1 | 19.735 | 0.8120 | 18.107 | 21.363 |
| dose_f | 2 | 26.100 | 0.8120 | 24.472 | 27.728 |
Pairwise comparisons of marginal means (Holm adjustment)
| Factor | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| supp | OJ - VC | 3.700 | 0.9376 | 3.946 | < .001 | 1.820 | 5.580 |
| dose_f | 0.5 - 1 | −9.130 | 1.148 | −7.951 | < .001 | −11.432 | −6.828 |
| dose_f | 0.5 - 2 | −15.495 | 1.148 | −13.493 | < .001 | −17.797 | −13.193 |
| dose_f | 1 - 2 | −6.365 | 1.148 | −5.543 | < .001 | −8.667 | −4.063 |
Simple effects of supp within dose_f
| Effect | F | df1 | df2 | p |
|---|---|---|---|---|
| supp | dose_f=0.5 | 10.451 | 1 | 54 | .002 |
| supp | dose_f=1 | 13.333 | 1 | 54 | < .001 |
| supp | dose_f=2 | 0.0024 | 1 | 54 | .961 |
Pairwise comparisons of supp within dose_f
| Within | Contrast | Difference | SE | t | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| dose_f=0.5 | OJ - VC | 5.250 | 1.624 | 3.233 | .002 | 1.994 | 8.506 |
| dose_f=1 | OJ - VC | 5.930 | 1.624 | 3.651 | < .001 | 2.674 | 9.186 |
| dose_f=2 | OJ - VC | −0.0800 | 1.624 | −0.0493 | .961 | −3.336 | 3.176 |
- Model: len ~ supp * dose_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 1dc19eb9e06d66ca
# Dataset: toothgrowth (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/toothgrowth.parquet", columns=["len", "supp", "dose_f"])
n_input = len(df)
df["supp"] = pd.Categorical(df["supp"], categories=["OJ", "VC"]) # stored level order
df["dose_f"] = pd.Categorical(df["dose_f"], categories=["0.5", "1", "2"]) # stored level order
df = df.dropna(subset=["len", "supp", "dose_f"]) # listwise deletion over the analysis columns
df["supp"] = df["supp"].cat.remove_unused_categories()
df["dose_f"] = df["dose_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, ["len", "supp", "dose_f"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
y = "len"
factor_cols = ["supp", "dose_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 = "2"
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 = "holm"
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 = "always"
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")})],
})
Check your reading
CheckpointCheck yourself
Which sentence fairly summarizes the Welch t test on route alone?
Show the answer
Answer: c
A p-value above 0.05 does not show the groups are the same, and a higher sample mean proves nothing alone. The interval says which gaps remain compatible with the data.
Check yourself
Why did accounting for dose sharpen the evidence about route?
Show the answer
Answer: a
The study has the same 60 animals. The two-way model explains part of the spread with dose, so less is left as unexplained noise. Extra variables do not always help: one unrelated to the outcome costs you a little.
Check yourself
What was the difference in mean growth, orange juice minus ascorbic acid? Give one decimal.
Show the answer
Answer: 3.7
Subtract the two group means. Report this number first: it is the answer to your question, in the outcome's own units.
Do it yourself
In the appRun the same comparison in the real app, on the same data: {{outcome}} by {{group}}. The walkthrough guides you through it; the second button opens the test for you to set up alone.
Recap
Recap- Write the question first. It decides which comparison counts.
- Look at the size of the gap and the spread inside groups before any test.
- Ask how big a gap luck alone produces; shuffling answers that directly.
- Report the gap with its interval. A p-value alone hides what the data leave open.
- Another variable can sharpen the comparison and raise new questions, like an interaction.
Concepts in this lesson