Reading any test output
Every result card has the same parts in the same order. Learn the reading order once, then use it on tests you have never met.
What runs in CodeSplash
- Two-sample t-test (Welch / Student, or z test) Verified in Python and R
- χ² test of independence Verified in Python and R
- One-way ANOVA (Welch / classic) Verified in Python and R
You will be able to
- Read a result card in a fixed order, from question to sentence
- Interpret a statistic with its degrees of freedom and a p-value
- Report an effect size and interval alongside any test
Read first
One reading order
ReadWhatever the test, read its output in the same order.
- The question. What does say?
- The statistic and its degrees of freedom. How far is the data from , on what scale?
- The p-value. How surprising is that if holds?
- The effect size and interval. How big, and how precisely known?
- The checks. Which assumptions passed?
- The sentence. What would you tell someone?
Each step changes how you read the next.
Put the order to work
CheckpointCheck yourself
Put these parts of a result card in reading order.
Show the answer
The order:
- The question the test answers
- The statistic and degrees of freedom
- The p-value
- The effect size and interval
- The assumption checks
- A plain sentence for your reader
You read the question first so the rest has meaning, and the effect before the checks so you know what might be at risk.
A card you know
ReadToothGrowth with the Welch t test:
| Part | Reads |
|---|---|
| Statistic | = 1.92, = 55.3 |
| p-value | p = .061 |
| Effect | = 0.488 |
| Interval | −0.17 to 7.57 |
| Checks | Levene p = .275 |
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])},
)],
})
The interval crosses zero, and it also reaches well past 3.70. So the data are compatible with no difference and with a sizeable one.
A card you may not know
PredictPredict first
A test of hair color by eye color in 592 students gives = 138 on 9 degrees of freedom, p < .001. Using only the reading order, what would you say before you see the effect size?
Reveal
You can't say yet: a big grows with . The effect size settles it: Cramér's VCramér's VAssociation strength in a contingency table, from 0 (none) to 1 (perfect). = 0.279, a clear but moderate association. The smallest expected count is 7.68, which answers the check.
And another
ReadWelch ANOVA on PlantGrowth reports = 5.18 on 2 and 17.1 degrees of freedom, p = .017, with = 0.204.
Two things are new. There are two degrees of freedom, because an F compares a between-groups and a within-groups variance. And a non-integer second one tells you Welch's correction was applied.
F(2, 17.13) = 5.18, p = .017, ω² = .20
- F
- 5.181
- df1
- 2
- df2
- 17.128
- p
- .017
Effect size
- ω² 0.2041 · large
- η² 0.2641 · large
- ε² 0.2096
Plots
View data
| group | weight |
|---|---|
| ctrl | 4.170 |
| ctrl | 5.580 |
| ctrl | 5.180 |
| ctrl | 6.110 |
| ctrl | 4.500 |
| ctrl | 4.610 |
| ctrl | 5.170 |
| ctrl | 4.530 |
| ctrl | 5.330 |
| ctrl | 5.140 |
| trt1 | 4.810 |
| trt1 | 4.170 |
| trt1 | 4.410 |
| trt1 | 3.590 |
| trt1 | 5.870 |
| trt1 | 3.830 |
| trt1 | 6.030 |
| trt1 | 4.890 |
| trt1 | 4.320 |
| trt1 | 4.690 |
| trt2 | 6.310 |
| trt2 | 5.120 |
| trt2 | 5.540 |
| trt2 | 5.500 |
| trt2 | 5.370 |
| trt2 | 5.290 |
| trt2 | 4.920 |
| trt2 | 6.150 |
| trt2 | 5.800 |
| trt2 | 5.260 |
View data
| Difference in weight | CI high | Comparison | CI low |
|---|---|---|---|
| −0.3710 | 0.4301 | trt1-ctrl | −1.172 |
| 0.4940 | 1.089 | trt2-ctrl | −0.1006 |
| 0.8650 | 1.616 | trt2-trt1 | 0.1135 |
Assumptions
- Normality of residuals — Shapiro–Wilk W = 0.966, p = .438.
- Equal variances — Welch's ANOVA does not assume equal variances (Brown–Forsythe F = 1.12, p = .341).
Descriptives
| group | n | Mean | SD | SE |
|---|---|---|---|---|
| ctrl | 10 | 5.032 | 0.5831 | 0.1844 |
| trt1 | 10 | 4.661 | 0.7937 | 0.2510 |
| trt2 | 10 | 5.526 | 0.4426 | 0.1400 |
Games–Howell
| Comparison | Difference | 95% CI low | 95% CI high | p (adjusted) |
|---|---|---|---|---|
| trt1-ctrl | −0.3710 | −1.172 | 0.4301 | .475 |
| trt2-ctrl | 0.4940 | −0.1006 | 1.089 | .113 |
| trt2-trt1 | 0.8650 | 0.1135 | 1.616 | .024 |
- Welch's one-way ANOVA; effect sizes from the classic sums of squares; post hoc differences are later − earlier level.
The exact R script · R R version 4.5.1 (2025-06-13)
# One-way ANOVA (Welch / classic)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.oneway 1.2.2 · spec 9396dc3962ec49cc
# Dataset: plantgrowth (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/plantgrowth.parquet", col_select = c("weight", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("ctrl", "trt1", "trt2")) # stored level order
df <- df[stats::complete.cases(df[c("weight", "group")]), , 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("weight", "group")) # 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
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 <- "weight"
g <- "group"
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
d <- data.frame(y = df[[y]], g = df[[g]])
levels_g <- levels(d$g)
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
if (any(is.infinite(d$y))) cs_error("CS_E_NOT_FINITE", column = y, count = sum(is.infinite(d$y)))
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = y)
ns <- as.vector(table(d$g))
for (i in seq_len(k)) { # every variant needs a variance in each group (oneway.test: two values per group)
if (ns[i] < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = levels_g[i], n = ns[i])
}
means <- as.vector(tapply(d$y, d$g, mean))
variances <- as.vector(tapply(d$y, d$g, var))
N <- sum(ns)
variant <- "welch" # welch (default) | brown_forsythe | alexander_govern: no equal-variance assumption; classic
posthoc_method <- "auto"
if (!TRUE) posthoc_method <- "none" # legacy switch: analyses saved before version 1.2
if (posthoc_method == "auto") posthoc_method <- if (variant == "classic") "tukey" else "games_howell" # match the omnibus test
posthoc_labels <- c(tukey = "Tukey–Kramer", scheffe = "Scheffé", lsd = "Fisher's protected LSD", games_howell = "Games–Howell",
tamhane_t2 = "Tamhane T2", dunnett_t3 = "Dunnett T3", uwh = "Ury–Wiggins–Hochberg")
conf <- 0.95
# Sums of squares (classic decomposition) for the effect sizes.
grand <- mean(d$y)
ss_between <- sum(ns * (means - grand)^2)
ss_within <- sum((ns - 1) * variances)
if (ss_within <= 1e-12 * sum((d$y - grand)^2)) { # no variation inside the groups: every F ratio is undefined
cs_error("CS_E_UNDEFINED", what = "One-way ANOVA", reason = sprintf("%s does not vary within any group", y))
}
if (variant %in% c("welch", "alexander_govern")) { # weights are 1 / variance: a group without variation makes them infinite
for (i in seq_len(k)) {
if (length(unique(d$y[d$g == levels_g[i]])) == 1) {
cs_error("CS_E_UNDEFINED", what = if (variant == "welch") "Welch's ANOVA" else "The Alexander–Govern test",
reason = sprintf("%s does not vary within %s", y, levels_g[i]))
}
}
}
ss_total <- ss_between + ss_within
df1 <- k - 1
df_within <- N - k
ms_within <- ss_within / df_within
eta_sq <- ss_between / ss_total
omega_sq <- (ss_between - df1 * ms_within) / (ss_total + ms_within)
epsilon_sq <- (ss_between - df1 * ms_within) / ss_total
chisq <- NULL
df1_mehrotra <- NULL
p_mehrotra <- NULL
if (variant == "brown_forsythe") {
bf <- cs_brown_forsythe(split(d$y, d$g)) # Brown & Forsythe (1974) F* (onewaytests::bf.test)
f <- bf$f
df2 <- bf$df2
p <- bf$p
df1_mehrotra <- bf$df1_mehrotra # Mehrotra (1997) corrected df
p_mehrotra <- bf$p_mehrotra
} else if (variant == "alexander_govern") {
ag <- cs_alexander_govern(split(d$y, d$g)) # Alexander & Govern (1994), A ~ chi^2(k - 1)
f <- NULL
df2 <- NULL
p <- ag$p
chisq <- ag$statistic
} else {
res <- oneway.test(y ~ g, data = d, var.equal = variant == "classic") # Welch (1951) unless classic
f <- unname(res$statistic)
df2 <- unname(res$parameter[2])
p <- res$p.value
}
# %% Post hoc
pairs <- list()
if (posthoc_method != "none" && k > 2) {
# The shared post hoc twins (cs_* <-> codesplash.stats.posthoc, posthoc.pairwise) report earlier - later;
# this card reports later - earlier, so flip the sign and the interval.
groups <- split(d$y, d$g)
rows <- switch(posthoc_method,
tukey = cs_tukey_kramer(groups, levels_g, conf),
scheffe = cs_scheffe(groups, levels_g, conf)$rows,
lsd = cs_lsd(groups, levels_g, conf)$rows, # gated by the classic F
games_howell = cs_games_howell(groups, levels_g, conf),
tamhane_t2 = cs_tamhane_t2(groups, levels_g, conf),
dunnett_t3 = cs_dunnett_t3(groups, levels_g, conf),
cs_ury_wiggins_hochberg(groups, levels_g, conf = conf))
pairs <- lapply(seq_len(nrow(rows)), function(r) list(pair = paste(rows$b[r], rows$a[r], sep = "-"), diff = -rows$estimate[r],
p_adj = rows$p_adj[r], ci_low = -rows$ci_high[r], ci_high = -rows$ci_low[r]))
}
# %% Assumptions
assumptions <- list()
resid <- d$y - ave(d$y, d$g)
sw <- if (N >= 3 && N <= 5000 && diff(range(resid)) > 0) shapiro.test(resid) else NULL
if (is.null(sw)) {
assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = "info", detail = "Shapiro–Wilk not computed (needs 3–5,000 residuals).")
} else {
status <- if (sw$p.value >= 0.05) "pass" else if (min(ns) >= 30) "info" else "warn"
assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = status, statistic = unname(sw$statistic), p = sw$p.value,
detail = paste0(sprintf("Shapiro–Wilk W = %.3f, %s", sw$statistic, cs_fmt_p(sw$p.value)),
if (status == "warn") "; consider Kruskal–Wallis." else "."))
}
lev <- oneway.test(abs(d$y - ave(d$y, d$g, FUN = median)) ~ d$g, var.equal = TRUE) # Brown-Forsythe
lev_f <- unname(lev$statistic)
lev_p <- lev$p.value
if (variant == "classic") {
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 ANOVA is safer." else ".")
} else {
status <- "info"
detail <- sprintf("Welch's ANOVA does not assume equal variances (Brown–Forsythe F = %.2f, %s).", lev_f, cs_fmt_p(lev_p))
}
assumptions[[2]] <- 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(d$y, as.integer(d$g) - 1L, 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 (variant != "classic") {
status <- "info"
detail <- sprintf("Welch's ANOVA 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 ANOVA 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(ns) < 5) warnings <- c(warnings, "A group has fewer than 5 values.")
normality_p <- NULL
if (normality_test != "shapiro_wilk") {
ns_ <- normality_selected(list(resid), "Normality of residuals", min(ns) < 30)
normality_p <- ns_$p
assumptions <- lapply(assumptions, function(a) if (a$key == "normality") ns_$row else a)
}
# %% Result
alpha <- 1 - conf
size <- magnitude(omega_sq, c(0.01, 0.06, 0.14))
name <- c(welch = "Welch's one-way ANOVA", brown_forsythe = "Brown–Forsythe test of means",
alexander_govern = "Alexander–Govern test", classic = "One-way ANOVA")[[variant]]
significance <- if (p < alpha) {
sprintf("The group means differ significantly (%s).", cs_fmt_p(p))
} else {
sprintf("The data are compatible with equal means (%s).", cs_fmt_p(p))
}
summary <- sprintf("Mean %s across %d groups of %s ranged from %.2f to %.2f. %s %s accounts for an estimated %.0f%% of the variance in %s (ω² = %.2f, %s).",
y, k, g, min(means), max(means), significance, g, omega_sq * 100, y, omega_sq, size)
if (length(pairs)) {
n_sig <- sum(vapply(pairs, function(r) r$p_adj < alpha, logical(1)))
summary <- paste(summary, sprintf("%d of %d pairwise differences are significant (%s).", n_sig, length(pairs),
posthoc_labels[[posthoc_method]]))
}
values <- list(f = f, df1 = df1, df2 = df2, p = p, k = k, n = N, chisq = chisq, df1_mehrotra = df1_mehrotra, p_mehrotra = p_mehrotra,
eta_sq = eta_sq, omega_sq = omega_sq, epsilon_sq = epsilon_sq,
ss_between = ss_between, ss_within = ss_within, levene_f = lev_f, levene_p = lev_p,
sw_p_resid = if (is.null(sw)) NULL else sw$p.value)
for (r in pairs) {
for (key in c("diff", "p_adj", "ci_low", "ci_high")) values[[sprintf("%s[%s]", key, r$pair)]] <- r[[key]]
}
pct <- sprintf("%.0f%%", conf * 100)
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")),
rows = data.frame(group = levels_g, n = ns, mean = means, sd = sqrt(variances), se = sqrt(variances / ns))
))
if (length(pairs)) {
tables[[2]] <- list(
key = "posthoc", title = posthoc_labels[[posthoc_method]],
columns = list(list(key = "pair", label = "Comparison", type = "string"), list(key = "diff", label = "Difference", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "p_adj", label = "p (adjusted)", type = "pvalue")),
rows = pairs
)
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
values$max_interaction_order <- 1
if (!is.null(normality_p)) values$normality_p <- normality_p
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
method = "anova.oneway",
methodVersion = "1.2.2",
title = name,
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = summary,
apa = if (variant == "alexander_govern") sprintf("χ²(%d) = %s, %s, ω² = %s", df1, cs_fmt_num(chisq), cs_fmt_p(p), cs_fmt_num(omega_sq, leading_zero = FALSE))
else sprintf("F(%d, %s) = %s, %s, ω² = %s", df1, if (variant == "classic") sprintf("%.0f", df2) else sprintf("%.2f", df2),
cs_fmt_num(f), cs_fmt_p(p), cs_fmt_num(omega_sq, leading_zero = FALSE)),
statistics = c(if (variant == "alexander_govern") list(list(key = "chisq", label = "A (χ²)", value = chisq), list(key = "df1", label = "df", value = df1))
else list(list(key = "f", label = if (variant == "brown_forsythe") "F*" else "F", value = f), list(key = "df1", label = "df1", value = df1),
list(key = "df2", label = "df2", value = df2)),
list(list(key = "p", label = "p", value = p, format = "p"))),
tables = tables,
effectSizes = list(
list(key = "omega_sq", label = "ω²", value = omega_sq, method = "(SSb − df1·MSw) / (SSt + MSw)", magnitude = size, ruleSet = "Cohen (1988)"),
list(key = "eta_sq", label = "η²", value = eta_sq, method = "SSb / SSt", magnitude = magnitude(eta_sq, c(0.01, 0.06, 0.14)), ruleSet = "Cohen (1988)"),
list(key = "epsilon_sq", label = "ε²", value = epsilon_sq, method = "(SSb − df1·MSw) / SSt")
),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("%s; effect sizes from the classic sums of squares; post hoc differences are later − earlier level.", name)),
if (variant == "brown_forsythe") list(sprintf("Mehrotra's (1997) corrected numerator df = %.3f gives %s.", df1_mehrotra, cs_fmt_p(p_mehrotra))) else list()),
values = values,
charts = c(list(cs_chart("distribution", "raincloud", sprintf("%s by %s", y, g),
list(y = cs_col(y, df[[y]][chart_rows]), group = cs_col(g, as.character(df[[g]][chart_rows]), levels = levels_g)))),
if (length(pairs)) list(cs_chart("differences", "forest", sprintf("Differences in mean %s (%.0f%% simultaneous CI)", y, conf * 100), list(
label = cs_col("Comparison", vapply(pairs, function(x) x$pair, ""), "categorical"),
estimate = cs_col(sprintf("Difference in %s", y), vapply(pairs, function(x) x$diff, 0), "numeric"),
low = cs_col("CI low", vapply(pairs, function(x) x$ci_low, 0), "numeric"),
high = cs_col("CI high", vapply(pairs, function(x) x$ci_high, 0), "numeric")), controls = list(reference = 0))) else list())
))
F(2, 17.13) = 5.18, p = .017, ω² = .20
- F
- 5.181
- df1
- 2
- df2
- 17.128
- p
- .017
Effect size
- ω² 0.2041 · large
- η² 0.2641 · large
- ε² 0.2096
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of residuals — Shapiro–Wilk W = 0.966, p = .438.
- Equal variances — Welch's ANOVA does not assume equal variances (Brown–Forsythe F = 1.12, p = .341).
Descriptives
| group | n | Mean | SD | SE |
|---|---|---|---|---|
| ctrl | 10 | 5.032 | 0.5831 | 0.1844 |
| trt1 | 10 | 4.661 | 0.7937 | 0.2510 |
| trt2 | 10 | 5.526 | 0.4426 | 0.1400 |
Games–Howell
| Comparison | Difference | 95% CI low | 95% CI high | p (adjusted) |
|---|---|---|---|---|
| trt1-ctrl | −0.3710 | −1.172 | 0.4301 | .475 |
| trt2-ctrl | 0.4940 | −0.1006 | 1.089 | .113 |
| trt2-trt1 | 0.8650 | 0.1135 | 1.616 | .024 |
- Welch's one-way ANOVA; effect sizes from the classic sums of squares; post hoc differences are later − earlier level.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One-way ANOVA (Welch / classic)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.oneway 1.2.2 · spec 9396dc3962ec49cc
# Dataset: plantgrowth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import means as csm
from codesplash.stats import posthoc as ph
# %% Data
df = pd.read_parquet("tests/parity/fixtures/plantgrowth.parquet", columns=["weight", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["ctrl", "trt1", "trt2"]) # stored level order
df = df.dropna(subset=["weight", "group"]) # listwise deletion over the analysis columns
df["group"] = df["group"].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, ["weight", "group"]) # 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 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 = "weight", "group"
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
levels = [str(lv) for lv in df[g].cat.categories]
k = len(levels)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
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 df[y].nunique() < 2:
cs.cs_error("CS_E_CONSTANT", column=y)
groups = [df.loc[df[g] == lv, y].to_numpy(dtype=float) for lv in df[g].cat.categories]
ns = np.array([len(x) for x in groups])
for lv, n_lv in zip(levels, ns): # every variant needs a variance in each group (R's oneway.test: two values per group)
if n_lv < 2:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=lv, n=int(n_lv))
means = np.array([x.mean() for x in groups])
variances = np.array([x.var(ddof=1) if len(x) > 1 else np.nan for x in groups])
N = int(ns.sum())
variant = "welch" # welch (default) | brown_forsythe | alexander_govern: no equal-variance assumption; classic
posthoc_method = "auto"
if not True: # legacy switch: analyses saved before version 1.2 ("posthoc: false")
posthoc_method = "none"
if posthoc_method == "auto": # match the omnibus test
posthoc_method = "tukey" if variant == "classic" else "games_howell"
POSTHOC_LABELS = {"tukey": "Tukey–Kramer", "scheffe": "Scheffé", "lsd": "Fisher's protected LSD", "games_howell": "Games–Howell",
"tamhane_t2": "Tamhane T2", "dunnett_t3": "Dunnett T3", "uwh": "Ury–Wiggins–Hochberg"}
conf = 0.95
# Sums of squares (classic decomposition) for the effect sizes.
grand = df[y].mean()
ss_between = float((ns * (means - grand) ** 2).sum())
ss_within = float(((ns - 1) * variances).sum())
if ss_within <= 1e-12 * float(((df[y] - grand) ** 2).sum()): # no variation inside the groups: every F ratio is undefined
cs.cs_error("CS_E_UNDEFINED", what="One-way ANOVA", reason=f"{y} does not vary within any group")
if variant in ("welch", "alexander_govern"): # weights are 1 / variance: a group without variation makes them infinite
for lv, x in zip(levels, groups):
if len(np.unique(x)) == 1:
cs.cs_error("CS_E_UNDEFINED", what="Welch's ANOVA" if variant == "welch" else "The Alexander–Govern test",
reason=f"{y} does not vary within {lv}")
ss_total = ss_between + ss_within
df1, df_within = k - 1, N - k
ms_within = ss_within / df_within
eta_sq = ss_between / ss_total
omega_sq = (ss_between - df1 * ms_within) / (ss_total + ms_within)
epsilon_sq = (ss_between - df1 * ms_within) / ss_total
chisq = df1_mehrotra = p_mehrotra = None
if variant == "welch":
res = stats.f_oneway(*groups, equal_var=False) # Welch (1951)
w = ns / variances
tmp = float((((1 - w / w.sum()) ** 2) / (ns - 1)).sum())
df2 = (k**2 - 1) / (3 * tmp)
f, p = float(res.statistic), float(res.pvalue)
elif variant == "brown_forsythe":
bf = csm.brown_forsythe(groups) # Brown & Forsythe (1974) F* (onewaytests::bf.test)
f, df2, p = bf["f"], bf["df2"], bf["p"]
df1_mehrotra, p_mehrotra = bf["df1_mehrotra"], bf["p_mehrotra"] # Mehrotra (1997) corrected df
elif variant == "alexander_govern":
ag = csm.alexander_govern(groups) # Alexander & Govern (1994), A ~ χ²(k − 1)
f, df2, p, chisq = None, None, ag["p"], ag["statistic"]
else:
res = stats.f_oneway(*groups) # classic F (equal variances)
df2 = float(df_within)
f, p = float(res.statistic), float(res.pvalue)
# %% Post hoc
pairs = []
if posthoc_method != "none" and k > 2:
# The shared post hoc twins (codesplash.stats.posthoc ↔ cs_*, posthoc.pairwise) report earlier − later;
# this card reports later − earlier, so flip the sign and the interval.
if posthoc_method == "tukey":
rows = ph.tukey_kramer(groups, levels, conf)
elif posthoc_method == "scheffe":
rows, _crit = ph.scheffe(groups, levels, conf)
elif posthoc_method == "lsd":
rows, _f, _p, _crit = ph.lsd(groups, levels, conf) # gated by the classic F
elif posthoc_method == "games_howell":
rows = ph.games_howell(groups, levels, conf)
elif posthoc_method == "tamhane_t2":
rows = ph.tamhane_t2(groups, levels, conf)
elif posthoc_method == "dunnett_t3":
rows = ph.dunnett_t3(groups, levels, conf)
else:
rows = ph.ury_wiggins_hochberg(groups, levels, conf=conf)
pairs = [{"pair": f"{r['b']}-{r['a']}", "diff": -float(r["estimate"]), "p_adj": float(r["p_adj"]),
"ci_low": -float(r["ci_high"]), "ci_high": -float(r["ci_low"])} for r in rows]
# %% Assumptions
assumptions = []
resid = np.concatenate([x - x.mean() for x in groups])
sw = stats.shapiro(resid) if 3 <= N <= 5000 and np.ptp(resid) > 0 else None
if sw is None:
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "info", "detail": "Shapiro–Wilk not computed (needs 3–5,000 residuals)."})
else:
status = "pass" if sw.pvalue >= 0.05 else ("info" if ns.min() >= 30 else "warn")
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": status, "statistic": float(sw.statistic), "p": float(sw.pvalue),
"detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}" + ("; consider Kruskal–Wallis." if status == "warn" else ".")})
lev = stats.levene(*groups, center="median") # Brown–Forsythe
if variant == "classic":
status = "warn" if lev.pvalue < 0.05 else "pass"
detail = f"Brown–Forsythe F = {lev.statistic:.2f}, {cs.fmt_p(lev.pvalue)}" + ("; Welch's ANOVA is safer." if lev.pvalue < 0.05 else ".")
else:
status, detail = "info", f"Welch's ANOVA 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(groups), np.repeat(np.arange(k), ns.astype(int)), 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 variant != "classic":
status, detail = "info", f"Welch's ANOVA does not assume equal variances ({shown})."
else:
status = "warn" if lev_p < 0.05 else "pass"
detail = shown + ("; " + "Welch's ANOVA" + " 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 ns.min() < 5:
warnings.append("A group has fewer than 5 values.")
normality_p = None
if normality_test != "shapiro_wilk":
_row, normality_p = normality_selected([resid], "Normality of residuals", ns.min() < 30)
assumptions = [_row if a["key"] == "normality" else a for a in assumptions]
# %% Result
alpha = 1 - conf
size = magnitude(omega_sq, (0.01, 0.06, 0.14))
name = {"welch": "Welch's one-way ANOVA", "brown_forsythe": "Brown–Forsythe test of means",
"alexander_govern": "Alexander–Govern test", "classic": "One-way ANOVA"}[variant]
significance = (
f"The group means differ significantly ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with equal means ({cs.fmt_p(p)})."
)
summary = (
f"Mean {y} across {k} groups of {g} ranged from {means.min():.2f} to {means.max():.2f}. {significance} "
f"{g} accounts for an estimated {omega_sq:.0%} of the variance in {y} (ω² = {omega_sq:.2f}, {size})."
)
significant_pairs = [r["pair"] for r in pairs if r["p_adj"] < alpha]
if pairs:
summary += f" {len(significant_pairs)} of {len(pairs)} pairwise differences are significant ({POSTHOC_LABELS[posthoc_method]})."
values = {
"f": f, "df1": float(df1), "df2": None if df2 is None else float(df2), "p": p, "k": k, "n": N,
"chisq": chisq, "df1_mehrotra": df1_mehrotra, "p_mehrotra": p_mehrotra,
"eta_sq": eta_sq, "omega_sq": omega_sq, "epsilon_sq": epsilon_sq,
"ss_between": ss_between, "ss_within": ss_within,
"levene_f": lev_f, "levene_p": lev_p, "sw_p_resid": None if sw is None else float(sw.pvalue),
}
for r in pairs:
values.update({f"{key}[{r['pair']}]": r[key] for key in ("diff", "p_adj", "ci_low", "ci_high")})
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"}],
"rows": [{"group": lv, "n": int(n), "mean": float(m), "sd": float(np.sqrt(v)), "se": float(np.sqrt(v / n))}
for lv, n, m, v in zip(levels, ns, means, variances)],
}]
if pairs:
tables.append({
"key": "posthoc", "title": POSTHOC_LABELS[posthoc_method],
"columns": [{"key": "pair", "label": "Comparison", "type": "string"}, {"key": "diff", "label": "Difference", "type": "number"},
{"key": "ci_low", "label": f"{conf:.0%} CI low", "type": "number"}, {"key": "ci_high", "label": f"{conf:.0%} CI high", "type": "number"},
{"key": "p_adj", "label": "p (adjusted)", "type": "pvalue"}],
"rows": pairs,
})
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
values["max_interaction_order"] = 1
if normality_p is not None:
values["normality_p"] = normality_p
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
"method": "anova.oneway",
"methodVersion": "1.2.2",
"title": name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": N,
"summary": summary,
"apa": (f"χ²({df1}) = {cs.fmt_num(chisq)}, {cs.fmt_p(p)}, ω² = {cs.fmt_num(omega_sq, leading_zero=False)}" if variant == "alexander_govern"
else f"F({df1}, {df2:.0f}) = {cs.fmt_num(f)}, {cs.fmt_p(p)}, ω² = {cs.fmt_num(omega_sq, leading_zero=False)}" if variant == "classic"
else f"F({df1}, {df2:.2f}) = {cs.fmt_num(f)}, {cs.fmt_p(p)}, ω² = {cs.fmt_num(omega_sq, leading_zero=False)}"),
"statistics": ([{"key": "chisq", "label": "A (χ²)", "value": chisq}, {"key": "df1", "label": "df", "value": df1}]
if variant == "alexander_govern" else
[{"key": "f", "label": "F*" if variant == "brown_forsythe" else "F", "value": f}, {"key": "df1", "label": "df1", "value": df1},
{"key": "df2", "label": "df2", "value": df2}])
+ [{"key": "p", "label": "p", "value": p, "format": "p"}],
"tables": tables,
"effectSizes": [
{"key": "omega_sq", "label": "ω²", "value": omega_sq, "method": "(SSb − df1·MSw) / (SSt + MSw)", "magnitude": size, "ruleSet": "Cohen (1988)"},
{"key": "eta_sq", "label": "η²", "value": eta_sq, "method": "SSb / SSt", "magnitude": magnitude(eta_sq, (0.01, 0.06, 0.14)), "ruleSet": "Cohen (1988)"},
{"key": "epsilon_sq", "label": "ε²", "value": epsilon_sq, "method": "(SSb − df1·MSw) / SSt"},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{name}; effect sizes from the classic sums of squares; post hoc differences are later − earlier level."]
+ ([f"Mehrotra's (1997) corrected numerator df = {df1_mehrotra:.3f} gives {cs.fmt_p(p_mehrotra)}."] if variant == "brown_forsythe" else []),
"values": values,
"charts": [cs.chart("distribution", "raincloud", f"{y} by {g}", {
"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=levels)})]
+ ([cs.chart("differences", "forest", f"Differences in mean {y} ({conf:.0%} simultaneous CI)", {
"label": cs.col("Comparison", [x["pair"] for x in pairs], "categorical"),
"estimate": cs.col(f"Difference in {y}", [x["diff"] for x in pairs], "numeric"),
"low": cs.col("CI low", [x["ci_low"] for x in pairs], "numeric"),
"high": cs.col("CI high", [x["ci_high"] for x in pairs], "numeric")}, controls={"reference": 0})] if pairs else []),
})
Check your understanding
CheckpointCheck yourself
A card reads . What does the non-integer tell you?
Show the answer
Answer: b
Pooled tests have whole-number degrees of freedom. Welch's formula shrinks them according to the two variances and group sizes.
Check yourself
With 2 million rows, a test gives p < .001 and Cramér's V = 0.02. What should your sentence say?
Show the answer
Answer: b
Large samples make small effects detectable. They don't make them large. p and V answer different questions.
Check yourself
A difference has a 95% interval from −1 to 40. Which sentence is best?
Show the answer
Answer: c
The interval's width is the message. Report the range; don't collapse it into a yes or no.
Use the card's own guide
In the appRun a test and open the Learn menu on the result. Choose Teach me: number the card in reading order to see this order drawn on your own card. Hold ⌥ to see an explanation for every number.
Recap
Recap- Read in order: question, statistic, p-value, effect and interval, checks, sentence.
- The statistic and p-value depend on sample size; the effect size says how big.
- A sentence that leaves out the size or the interval hasn't finished the job.
Concepts in this lesson