Kruskal–Wallis and other score tests
Replace values with scores, then run one test. Different scores suit different shapes, from Mood's median test to van der Waerden and Savage.
What runs in CodeSplash
- STAT024Kruskal–Wallis H test Runs in CodeSplash
- STAT025Mood median test Runs in CodeSplash
- STAT026Van der Waerden normal scores test Runs in CodeSplash
- STAT027Savage scores test Runs in CodeSplash
- Kruskal–Wallis test Verified in Python and R
You will be able to
- Describe Kruskal–Wallis as an ANOVA on ranks
- Match Mood, van der Waerden and Savage scores to the shapes they suit
- Interpret an effect size for H
ANOVA on ranks
ReadRank every value across all groups. If the groups are alike, their mean ranks should be close to the overall mean rank, . The Kruskal–WallisKruskal–Wallis testThe rank-based counterpart of one-way ANOVA, comparing mean ranks across three or more independent groups. statistic measures how far they stray:
With two groups this is exactly the Mann–Whitney test. Large is compared with on degrees of freedom.
Read the result
ReadH(2) = 7.99, p = .018, ε² = .28
- H
- 7.988
- df
- 2
- p
- .018
Effect size
- ε² 0.2755 · large
- η²_H 0.2218
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 |
Assumptions
- Comparable shapes — With similar shapes the test compares medians; otherwise it compares mean ranks (stochastic dominance).
Descriptives
| group | n | Median | Mean rank |
|---|---|---|---|
| ctrl | 10 | 5.155 | 14.750 |
| trt1 | 10 | 4.550 | 10.350 |
| trt2 | 10 | 5.435 | 21.400 |
Dunn (Holm)
| Comparison | Mean-rank difference | z | p | p (adjusted) |
|---|---|---|---|---|
| trt1-ctrl | −4.400 | −1.118 | .264 | .264 |
| trt2-ctrl | 6.650 | 1.689 | .091 | .182 |
| trt2-trt1 | 11.050 | 2.807 | .005 | .015 |
- H is tie-corrected; Dunn's z uses the tie-corrected variance; differences are later − earlier level.
- p-value: asymptotic.
The exact R script · R R version 4.5.1 (2025-06-13)
# Kruskal–Wallis test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.kruskal_wallis 1.3.0 · spec bd5b990ac76c5c2c
# 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)
# %% 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]
}
# %% Options
y <- "weight"
g <- "group"
`%||%` <- function(a, b) if (is.null(a)) b else a
alternative <- "any" %||% "any"
scores <- "wilcoxon" %||% "wilcoxon"
trend_test <- "jonckheere" %||% "jonckheere"
order_lv <- NULL # the order the alternative refers to (NULL = stored order)
peak <- NULL # umbrella peak level (NULL = unknown)
dose_scores <- FALSE
calibration <- "asymptotic" %||% "asymptotic"
n_perm <- as.integer(9999 %||% 9999)
seed <- 42 # shared Wichmann-Hill stream: Python draws the same permutations
posthoc <- TRUE
posthoc_method <- "dunn" %||% "dunn"
adjust <- "holm" %||% "holm"
# %% Groups, in the order the alternative refers to
present <- levels(df[[g]])
levels_g <- if (!is.null(order_lv)) {
wanted <- as.character(order_lv)
c(wanted[wanted %in% present], present[!present %in% wanted])
} else {
present
}
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
gi <- match(as.character(df[[g]]), levels_g) - 1L
yv <- as.double(df[[y]])
if (length(unique(yv)) < 2) cs_error("CS_E_CONSTANT", column = y) # every rank tied: the test statistic is 0/0
groups <- lapply(0:(k - 1L), function(j) yv[gi == j])
ns <- lengths(groups)
N <- sum(ns)
# %% Omnibus test (linear rank statistic; Wilcoxon scores give the tie-corrected H)
omni_scores <- if (alternative == "any") scores else "wilcoxon"
omni_cal <- if (alternative == "any") calibration else "asymptotic"
omni <- cs_linear_rank(yv, gi, scores = omni_scores, calibration = omni_cal, b = n_perm, seed = seed)
score_t <- omni$t
dof <- k - 1
median_ties <- "below"
median_yates <- FALSE
median_custom <- omni_scores == "median" && (median_ties != "below" || median_yates) # Stage 12.7 options
if (median_custom && omni_cal != "asymptotic") {
cs_error("CS_E_INVALID_OPTION", option = "The median test's tie rule and Yates correction", allowed = "used with the large-sample p-value", value = omni_cal)
}
if (omni_scores == "median") {
mood <- if (median_custom) cs_mood_median_ext(yv, gi, median_ties, median_yates) else cs_mood_median_chisq(yv, gi)
h <- mood$chisq # classical Pearson X^2 on the above / not-above table
p_omnibus <- if (omni_cal == "asymptotic") mood$p else omni$p_t
} else {
h <- score_t
p_omnibus <- omni$p_t
}
epsilon_sq <- score_t / (N - 1) # between-group share of the score variance (= H / (N - 1))
eta_sq_h <- (score_t - k + 1) / (N - k)
# %% Directional alternatives
test_labels <- c(kruskal_wallis = "Kruskal–Wallis H test", van_der_waerden = "Van der Waerden normal scores test",
savage = "Savage scores test", mood_median = "Mood's median test", jonckheere = "Jonckheere–Terpstra test",
cuzick = "Cuzick trend test", chacko = "Chacko order-restricted test", mack_wolfe = "Mack–Wolfe umbrella test")
symbols <- c(kruskal_wallis = "H", van_der_waerden = "T", savage = "T", mood_median = "χ²")
trend <- NULL
used_cal <- omni_cal
if (alternative == "any") {
test <- c(wilcoxon = "kruskal_wallis", normal = "van_der_waerden", savage = "savage", median = "mood_median")[[scores]]
p <- p_omnibus
} else if (alternative %in% c("increasing", "decreasing")) {
test <- trend_test
used_cal <- calibration
if (trend_test == "jonckheere") {
trend <- cs_jonckheere(yv, gi, alternative, calibration, n_perm, seed)
trend$stat <- trend$j
} else if (trend_test == "cuzick") {
weights <- NULL
if (dose_scores) {
weights <- suppressWarnings(as.double(levels_g))
if (anyNA(weights)) stop(sprintf("The labels of %s must be numbers to use them as doses", g))
}
trend <- cs_cuzick(yv, gi, weights, alternative, calibration, n_perm, seed)
trend$stat <- trend$t
} else if (trend_test == "chacko") {
trend <- cs_chacko(yv, gi, alternative, calibration, n_perm, seed)
trend$stat <- trend$h
trend["z"] <- list(NULL)
} else {
stop(sprintf("unknown trend test '%s'", trend_test))
}
p <- trend$p
} else if (alternative == "umbrella") {
test <- "mack_wolfe"
peak_idx <- if (!is.null(peak) && as.character(peak) %in% levels_g) match(as.character(peak), levels_g) - 1L else NULL
used_cal <- if (!is.null(peak_idx)) calibration else "permutation" # an unknown peak is calibrated jointly
trend <- cs_mack_wolfe(yv, gi, peak_idx, used_cal, n_perm, seed)
trend$stat <- trend$a
p <- trend$p
} else {
stop(sprintf("unknown alternative '%s'", alternative))
}
# %% Post hoc — after the omnibus Wilcoxon-score test only (twins of posthoc.pairwise)
ranks <- rank(yv)
mean_ranks <- vapply(0:(k - 1L), function(j) mean(ranks[gi == j]), numeric(1))
adjust_labels <- c(holm = "Holm", bonferroni = "Bonferroni", hochberg = "Hochberg", BH = "Benjamini–Hochberg", none = "unadjusted")
ph_labels <- c(dunn = "Dunn", conover_iman = "Conover–Iman", nemenyi = "Nemenyi", dscf = "Dwass–Steel–Critchlow–Fligner")
pairs <- list()
posthoc_label <- NULL
if (posthoc && posthoc_method != "none" && k > 2 && alternative == "any" && scores == "wilcoxon") {
rows <- switch(posthoc_method,
conover_iman = cs_conover_iman(groups, levels_g, adjust = adjust)$rows,
nemenyi = cs_nemenyi(groups, levels_g),
dscf = cs_dscf(groups, levels_g),
cs_dunn(groups, levels_g, adjust = adjust)
)
adj_label <- if (posthoc_method %in% c("dunn", "conover_iman")) adjust_labels[[adjust]] else "studentized range"
posthoc_label <- sprintf("%s (%s)", ph_labels[[posthoc_method]], adj_label)
# The twins report earlier - later; keep later - earlier like the Dunn keys of earlier versions.
for (r in seq_len(nrow(rows))) {
pairs[[r]] <- list(pair = paste(rows$b[r], rows$a[r], sep = "-"), diff = -rows$estimate[r], stat = -rows$stat[r],
p = rows$p[r], p_adj = rows$p_adj[r])
}
}
# %% Result
alpha <- 0.05
size <- magnitude(epsilon_sq, c(0.01, 0.06, 0.14))
medians <- vapply(groups, stats::median, numeric(1))
label <- test_labels[[test]]
stat_symbol <- if (test %in% names(symbols)) symbols[[test]] else "H"
values <- list(h = h, df = dof, p = p, p_omnibus = p_omnibus, n = N, k = k, epsilon_sq = epsilon_sq,
eta_sq_h = eta_sq_h, score_t = score_t, test = test, test_label = label, stat_symbol = stat_symbol,
alternative = alternative, calibration = used_cal)
order_text <- paste(levels_g, collapse = " < ")
if (alternative == "any") {
significance <- if (p < alpha) {
sprintf("At least one group tends to differ (%s).", cs_fmt_p(p))
} else {
sprintf("The data are compatible with identical distributions (%s).", cs_fmt_p(p))
}
summary <- sprintf("%s: median %s across %d groups of %s ranged from %.2f to %.2f. %s The effect is %s (ε² = %.2f).",
label, y, k, g, min(medians), max(medians), significance, size, epsilon_sq)
if (!is.null(omni$n_perm)) {
values$n_perm <- omni$n_perm
values$count <- omni$count_t
}
} else {
values$trend_stat <- trend$stat
if (!is.null(trend$z)) values$z <- trend$z
if (!is.null(trend$n_perm)) {
values$n_perm <- trend$n_perm
values$count <- trend$count
}
if (alternative == "umbrella") {
values$peak <- levels_g[trend$peak + 1L]
for (j in seq_len(k)) values[[sprintf("z_peak[%s]", levels_g[j])]] <- trend$z_by_peak[j]
where <- paste0("peak at ", values$peak, if (trend$peak_known) "" else " (estimated; calibrated over all peaks)")
summary <- paste0(sprintf("%s over %s, %s: z = %.2f, %s. ", label, order_text, where, trend$z, cs_fmt_p(p)),
if (p < alpha) "The response rises to the peak and then falls." else "No umbrella pattern is evident.")
} else {
if (test == "jonckheere") {
pairs_total <- 0
for (a in seq_len(k - 1)) for (b in (a + 1):k) pairs_total <- pairs_total + ns[a] * ns[b]
values$concordance <- trend$j / pairs_total
}
direction <- if (alternative == "increasing") "rises" else "falls"
summary <- paste0(sprintf("%s for a %s order %s: %s. ", label, alternative, order_text, cs_fmt_p(p)),
if (p < alpha) sprintf("%s %s across the ordered groups.", y, direction) else sprintf("No %s trend is evident.", alternative),
sprintf(" Omnibus Kruskal–Wallis %s.", cs_fmt_p(p_omnibus)))
}
}
if (length(pairs)) {
summary <- paste(summary, sprintf("%d of %d %s comparisons are significant.",
sum(vapply(pairs, function(r) r$p_adj < alpha, logical(1))), length(pairs), posthoc_label))
values$posthoc_label <- posthoc_label
}
stat_key <- if (posthoc_method == "dunn") "z" else "stat"
for (r in pairs) {
values[[sprintf("%s[%s]", stat_key, r$pair)]] <- r$stat
values[[sprintf("diff[%s]", r$pair)]] <- r$diff
values[[sprintf("p_unadj[%s]", r$pair)]] <- r$p
values[[sprintf("p_adj[%s]", r$pair)]] <- r$p_adj
}
desc_cols <- list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "median", label = "Median", type = "number"), list(key = "mean_rank", label = "Mean rank", type = "number"))
desc_rows <- data.frame(group = levels_g, n = ns, median = medians, mean_rank = mean_ranks)
if (alternative == "any" && scores %in% c("normal", "savage")) {
desc_cols[[length(desc_cols) + 1]] <- list(key = "mean_score", label = "Mean score", type = "number")
desc_rows$mean_score <- omni$mean_score
}
if (alternative == "any" && scores == "median") {
desc_cols[[length(desc_cols) + 1]] <- list(key = "above", label = "Above pooled median", type = "integer")
desc_rows$above <- mood$above
}
if (test == "cuzick") {
desc_cols[[length(desc_cols) + 1]] <- list(key = "weight", label = "Score", type = "number")
desc_rows$weight <- trend$weights
}
if (test == "chacko") {
desc_cols[[length(desc_cols) + 1]] <- list(key = "iso_rank", label = "Isotonic mean rank", type = "number")
desc_rows$iso_rank <- if (alternative == "increasing") trend$iso_ranks else rev(trend$iso_ranks)
}
tables <- list(list(key = "descriptives",
title = if (alternative == "any") "Descriptives" else sprintf("Groups in order (%s)", order_text),
columns = desc_cols, rows = desc_rows))
if (alternative == "umbrella") {
tables[[length(tables) + 1]] <- list(
key = "peaks", title = "Standardized statistic by candidate peak",
columns = list(list(key = "peak", label = "Peak", type = "string"), list(key = "z", label = "z", type = "number")),
rows = data.frame(peak = levels_g, z = trend$z_by_peak)
)
}
if (length(pairs)) {
stat_label <- c(dunn = "z", conover_iman = "t", nemenyi = "q", dscf = "q")[[posthoc_method]]
diff_label <- if (posthoc_method == "dscf") "Shift (Hodges–Lehmann)" else "Mean-rank difference"
tables[[length(tables) + 1]] <- list(
key = "posthoc", title = posthoc_label,
columns = list(list(key = "pair", label = "Comparison", type = "string"), list(key = "diff", label = diff_label, type = "number"),
list(key = "stat", label = stat_label, type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "p_adj", label = "p (adjusted)", type = "pvalue")),
rows = pairs
)
}
how <- if (!is.null(values$n_perm)) sprintf("%d Monte Carlo permutations, seed %d", as.integer(values$n_perm), as.integer(seed)) else "asymptotic"
if (alternative == "any") {
statistics <- list(list(key = "h", label = stat_symbol, value = h), list(key = "df", label = "df", value = dof),
list(key = "p", label = "p", value = p, format = "p"))
apa <- sprintf("%s(%d) = %s, %s, ε² = %s", stat_symbol, as.integer(dof), cs_fmt_num(h), cs_fmt_p(p), cs_fmt_num(epsilon_sq, leading_zero = FALSE))
} else {
stat_label <- c(jonckheere = "J", cuzick = "T (Cuzick)", chacko = "H̄ (isotonic)", mack_wolfe = "A (Mack–Wolfe)")[[test]]
statistics <- list(list(key = "trend_stat", label = stat_label, value = values$trend_stat))
if (!is.null(values$z)) statistics[[length(statistics) + 1]] <- list(key = "z", label = "z", value = values$z)
statistics <- c(statistics, list(list(key = "p", label = "p", value = p, format = "p"),
list(key = "p_omnibus", label = "p (omnibus Kruskal–Wallis)", value = p_omnibus, format = "p")))
apa <- if (test == "chacko") {
sprintf("%s, H̄ = %s, %s", label, cs_fmt_num(values$trend_stat), cs_fmt_p(p))
} else {
sprintf("%s, z = %s, %s", label, cs_fmt_num(values$z), cs_fmt_p(p))
}
}
effect_sizes <- list(
list(key = "epsilon_sq", label = "ε²", value = epsilon_sq, method = "T / (n − 1): between-group share of the rank-score variance",
magnitude = size, ruleSet = "Cohen (1988)"),
list(key = "eta_sq_h", label = "η²_H", value = eta_sq_h, method = "(T − k + 1) / (n − k)")
)
if (!is.null(values$concordance)) {
effect_sizes <- c(list(list(key = "concordance", label = "P(later > earlier)", value = values$concordance,
method = "J / Σ nₐn_b: probability a later group's value exceeds an earlier one's (ties ½); 0.5 = no trend")),
effect_sizes)
}
assumptions <- list(list(key = "shape", label = "Comparable shapes", status = "info",
detail = "With similar shapes the test compares medians; otherwise it compares mean ranks (stochastic dominance)."))
if (alternative != "any") {
assumptions[[2]] <- list(key = "order", label = "Order fixed in advance", status = "info",
detail = paste0("Order ", order_text,
if (alternative == "umbrella" && trend$peak_known) paste0(", peak ", values$peak) else "",
": valid only if chosen before seeing the data."))
}
if (test == "chacko" && used_cal == "asymptotic") {
warnings <- c(warnings, "The χ² reference for Chacko's statistic is conservative; choose the permutation p-value for an exact-size test.")
}
if (alternative == "umbrella" && is.null(peak) && calibration == "asymptotic") {
warnings <- c(warnings, "With an unknown peak the p-value is calibrated by permutation over all candidate peaks.")
}
notes <- c(
kruskal_wallis = "H is tie-corrected; Dunn's z uses the tie-corrected variance; differences are later − earlier level.",
van_der_waerden = "Normal scores Φ⁻¹(R/(N+1)) at midranks; T = (N − 1) Σ nⱼāⱼ² / Σ aᵢ² is referred to χ²ₖ₋₁.",
savage = "Savage scores Σ_{s=N−r+1}^{N} 1/s − 1, averaged over ties; T is referred to χ²ₖ₋₁.",
mood_median = "Pearson X² on counts above / not above the pooled median (values equal to the median count as not above).",
jonckheere = "J sums Mann–Whitney counts over ordered pairs (ties ½); the null variance is tie-corrected (Lehmann 1975).",
cuzick = "T = Σ wᵢRᵢ with group scores w; the variance is the exact permutation variance with ties.",
chacko = "Mean ranks are made monotone by pool-adjacent-violators before forming the Kruskal–Wallis statistic.",
mack_wolfe = "A sums Mann–Whitney counts up to the peak and reversed counts after it; null moments of Mack & Wolfe (1981)."
)[[test]]
if (median_custom) {
tie_text <- c(below = "count as not above", above = "count as above", drop = "are left out")[[median_ties]]
notes <- paste0("Pearson X² on counts above / not above the pooled median (values equal to the median ", tie_text,
if (median_yates && k == 2) "; Yates's continuity correction for two groups" else "", ").")
values$median_ties <- median_ties
values$median_yates <- median_yates
values$median_n_dropped <- mood$n_dropped
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
method = "nonparam.kruskal_wallis",
methodVersion = "1.3.0",
title = label,
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = summary,
apa = apa,
statistics = statistics,
tables = tables,
effectSizes = effect_sizes,
assumptions = assumptions,
warnings = warnings,
notes = list(notes, sprintf("p-value: %s.", how)),
values = values,
charts = 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))))
))
H(2) = 7.99, p = .018, ε² = .28
- H
- 7.988
- df
- 2
- p
- .018
Effect size
- ε² 0.2755 · large
- η²_H 0.2218
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Comparable shapes — With similar shapes the test compares medians; otherwise it compares mean ranks (stochastic dominance).
Descriptives
| group | n | Median | Mean rank |
|---|---|---|---|
| ctrl | 10 | 5.155 | 14.750 |
| trt1 | 10 | 4.550 | 10.350 |
| trt2 | 10 | 5.435 | 21.400 |
Dunn (Holm)
| Comparison | Mean-rank difference | z | p | p (adjusted) |
|---|---|---|---|---|
| trt1-ctrl | −4.400 | −1.118 | .264 | .264 |
| trt2-ctrl | 6.650 | 1.689 | .091 | .182 |
| trt2-trt1 | 11.050 | 2.807 | .005 | .015 |
- H is tie-corrected; Dunn's z uses the tie-corrected variance; differences are later − earlier level.
- p-value: asymptotic.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kruskal–Wallis test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.kruskal_wallis 1.3.0 · spec bd5b990ac76c5c2c
# 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 linear_rank, rank_tests
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)
# %% 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]
# %% Options
y, g = "weight", "group"
alternative = "any" or "any"
scores = "wilcoxon" or "wilcoxon"
trend_test = "jonckheere" or "jonckheere"
order = None # the order the alternative refers to (None = stored order)
peak = None # umbrella peak level (None = unknown)
dose_scores = False
calibration = "asymptotic" or "asymptotic"
n_perm = int(9999 or 9999)
seed = 42 # shared Wichmann–Hill stream: R draws the same permutations
posthoc = True
posthoc_method = "dunn" or "dunn"
adjust = "holm" or "holm"
# %% Groups, in the order the alternative refers to
present = [str(lv) for lv in df[g].cat.categories]
if order:
wanted = [str(lv) for lv in order]
levels = [lv for lv in wanted if lv in present] + [lv for lv in present if lv not in wanted]
else:
levels = present
k = len(levels)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
gi = df[g].astype(str).map({lv: i for i, lv in enumerate(levels)}).to_numpy(dtype=np.int64)
yv = df[y].to_numpy(dtype=float)
if len(np.unique(yv)) < 2: # every rank tied: the test statistic is 0/0
cs.cs_error("CS_E_CONSTANT", column=y)
groups = [yv[gi == j] for j in range(k)]
ns = np.array([len(x) for x in groups])
N = int(ns.sum())
# %% Omnibus test (linear rank statistic; Wilcoxon scores give the tie-corrected H)
omni_scores = scores if alternative == "any" else "wilcoxon"
omni_cal = calibration if alternative == "any" else "asymptotic"
omni = linear_rank.linear_rank(yv, gi, scores=omni_scores, calibration=omni_cal, b=n_perm, seed=seed)
score_t = omni["t"]
dof = k - 1
median_ties, median_yates = "below", False
median_custom = omni_scores == "median" and (median_ties != "below" or median_yates) # Stage 12.7 options
if median_custom and omni_cal != "asymptotic":
cs.cs_error("CS_E_INVALID_OPTION", option="The median test's tie rule and Yates correction", allowed="used with the large-sample p-value", value=omni_cal)
if omni_scores == "median":
if median_custom:
from codesplash.stats import stat_options as csopt
mood = csopt.mood_median_ext(yv, gi, median_ties, median_yates)
else:
mood = linear_rank.mood_median_chisq(yv, gi)
h = mood["chisq"] # classical Pearson X² on the above / not-above table
p_omnibus = mood["p"] if omni_cal == "asymptotic" else omni["p_t"]
else:
h = score_t
p_omnibus = omni["p_t"]
epsilon_sq = score_t / (N - 1) # between-group share of the score variance (= H / (N − 1))
eta_sq_h = (score_t - k + 1) / (N - k)
# %% Directional alternatives
TEST_LABELS = {
"kruskal_wallis": "Kruskal–Wallis H test", "van_der_waerden": "Van der Waerden normal scores test",
"savage": "Savage scores test", "mood_median": "Mood's median test", "jonckheere": "Jonckheere–Terpstra test",
"cuzick": "Cuzick trend test", "chacko": "Chacko order-restricted test", "mack_wolfe": "Mack–Wolfe umbrella test",
}
SYMBOLS = {"kruskal_wallis": "H", "van_der_waerden": "T", "savage": "T", "mood_median": "χ²"}
trend = None
used_cal = omni_cal
if alternative == "any":
test = {"wilcoxon": "kruskal_wallis", "normal": "van_der_waerden", "savage": "savage", "median": "mood_median"}[scores]
p = p_omnibus
elif alternative in ("increasing", "decreasing"):
test = trend_test
used_cal = calibration
if trend_test == "jonckheere":
trend = rank_tests.jonckheere(yv, gi, alternative, calibration, n_perm, seed)
trend["stat"] = trend["j"]
elif trend_test == "cuzick":
weights = None
if dose_scores:
try:
weights = [float(lv) for lv in levels]
except ValueError:
raise ValueError(f"The labels of {g} must be numbers to use them as doses") from None
trend = rank_tests.cuzick(yv, gi, weights, alternative, calibration, n_perm, seed)
trend["stat"] = trend["t"]
elif trend_test == "chacko":
trend = rank_tests.chacko(yv, gi, alternative, calibration, n_perm, seed)
trend["stat"] = trend["h"]
trend["z"] = None
else:
raise ValueError(f"unknown trend test {trend_test!r}")
p = trend["p"]
elif alternative == "umbrella":
test = "mack_wolfe"
peak_idx = levels.index(str(peak)) if peak is not None and str(peak) in levels else None
used_cal = calibration if peak_idx is not None else "permutation" # an unknown peak is calibrated jointly
trend = rank_tests.mack_wolfe(yv, gi, peak_idx, used_cal, n_perm, seed)
trend["stat"] = trend["a"]
p = trend["p"]
else:
raise ValueError(f"unknown alternative {alternative!r}")
# %% Post hoc — after the omnibus Wilcoxon-score test only (twins of posthoc.pairwise)
ranks = stats.rankdata(yv)
mean_ranks = [float(ranks[gi == j].mean()) for j in range(k)]
ADJUST_LABELS = {"holm": "Holm", "bonferroni": "Bonferroni", "hochberg": "Hochberg", "BH": "Benjamini–Hochberg", "none": "unadjusted"}
PH_LABELS = {"dunn": "Dunn", "conover_iman": "Conover–Iman", "nemenyi": "Nemenyi", "dscf": "Dwass–Steel–Critchlow–Fligner"}
pairs = []
posthoc_label = None
if posthoc and posthoc_method != "none" and k > 2 and alternative == "any" and scores == "wilcoxon":
if posthoc_method == "conover_iman":
rows, _ = ph.conover_iman(groups, levels, adjust=adjust)
elif posthoc_method == "nemenyi":
rows = ph.nemenyi(groups, levels)
elif posthoc_method == "dscf":
rows = ph.dscf(groups, levels)
else:
rows = ph.dunn(groups, levels, adjust=adjust)
adj_label = ADJUST_LABELS[adjust] if posthoc_method in ("dunn", "conover_iman") else "studentized range"
posthoc_label = f"{PH_LABELS[posthoc_method]} ({adj_label})"
# The twins report earlier − later; keep later − earlier like the Dunn keys of earlier versions.
for r in rows:
pairs.append({"pair": f"{r['b']}-{r['a']}", "diff": -float(r["estimate"]), "stat": -float(r["stat"]),
"p": float(r["p"]), "p_adj": float(r["p_adj"])})
# %% Result
alpha = 0.05
size = magnitude(epsilon_sq, (0.01, 0.06, 0.14))
medians = [float(np.median(x)) for x in groups]
label = TEST_LABELS[test]
values = {"h": h, "df": float(dof), "p": p, "p_omnibus": p_omnibus, "n": N, "k": k, "epsilon_sq": epsilon_sq,
"eta_sq_h": eta_sq_h, "score_t": score_t, "test": test, "test_label": label,
"stat_symbol": SYMBOLS.get(test, "H"), "alternative": alternative, "calibration": used_cal}
if alternative == "any":
significance = (f"At least one group tends to differ ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with identical distributions ({cs.fmt_p(p)}).")
summary = (f"{label}: median {y} across {k} groups of {g} ranged from {min(medians):.2f} to {max(medians):.2f}. "
f"{significance} The effect is {size} (ε² = {epsilon_sq:.2f}).")
if omni["n_perm"]:
values.update(n_perm=omni["n_perm"], count=omni["count_t"])
else:
values["trend_stat"] = float(trend["stat"])
if trend.get("z") is not None:
values["z"] = float(trend["z"])
if trend["n_perm"]:
values.update(n_perm=trend["n_perm"], count=trend["count"])
order_text = " < ".join(levels)
if alternative == "umbrella":
values["peak"] = levels[trend["peak"]]
for lv, zp in zip(levels, trend["z_by_peak"]):
values[f"z_peak[{lv}]"] = float(zp)
where = f"peak at {values['peak']}" + ("" if trend["peak_known"] else " (estimated; calibrated over all peaks)")
summary = (f"{label} over {order_text}, {where}: z = {trend['z']:.2f}, {cs.fmt_p(p)}. "
+ ("The response rises to the peak and then falls." if p < alpha else "No umbrella pattern is evident."))
else:
if test == "jonckheere":
pairs_total = sum(int(ns[a] * ns[b]) for a in range(k) for b in range(a + 1, k))
values["concordance"] = float(trend["j"] / pairs_total)
direction = "rises" if alternative == "increasing" else "falls"
summary = (f"{label} for a {alternative} order {order_text}: {cs.fmt_p(p)}. "
+ (f"{y} {direction} across the ordered groups." if p < alpha else f"No {alternative} trend is evident.")
+ f" Omnibus Kruskal–Wallis {cs.fmt_p(p_omnibus)}.")
if pairs:
summary += f" {sum(r['p_adj'] < alpha for r in pairs)} of {len(pairs)} {posthoc_label} comparisons are significant."
values["posthoc_label"] = posthoc_label
stat_key = "z" if posthoc_method == "dunn" else "stat"
for r in pairs:
values.update({f"{stat_key}[{r['pair']}]": r["stat"], f"diff[{r['pair']}]": r["diff"], f"p_unadj[{r['pair']}]": r["p"],
f"p_adj[{r['pair']}]": r["p_adj"]})
desc_cols = [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "median", "label": "Median", "type": "number"}, {"key": "mean_rank", "label": "Mean rank", "type": "number"}]
desc_rows = [{"group": lv, "n": int(n), "median": m, "mean_rank": r} for lv, n, m, r in zip(levels, ns, medians, mean_ranks)]
if alternative == "any" and scores in ("normal", "savage"):
desc_cols.append({"key": "mean_score", "label": "Mean score", "type": "number"})
for row, ms in zip(desc_rows, omni["mean_score"]):
row["mean_score"] = float(ms)
if alternative == "any" and scores == "median":
desc_cols.append({"key": "above", "label": "Above pooled median", "type": "integer"})
for row, a in zip(desc_rows, mood["above"]):
row["above"] = int(a)
if test == "cuzick":
desc_cols.append({"key": "weight", "label": "Score", "type": "number"})
for row, w in zip(desc_rows, trend["weights"]):
row["weight"] = float(w)
if test == "chacko":
desc_cols.append({"key": "iso_rank", "label": "Isotonic mean rank", "type": "number"})
iso = trend["iso_ranks"] if alternative == "increasing" else trend["iso_ranks"][::-1]
for row, r in zip(desc_rows, iso):
row["iso_rank"] = float(r)
tables = [{"key": "descriptives", "title": "Descriptives" if alternative == "any" else f"Groups in order ({' < '.join(levels)})",
"columns": desc_cols, "rows": desc_rows}]
if alternative == "umbrella":
tables.append({
"key": "peaks", "title": "Standardized statistic by candidate peak",
"columns": [{"key": "peak", "label": "Peak", "type": "string"}, {"key": "z", "label": "z", "type": "number"}],
"rows": [{"peak": lv, "z": float(zp)} for lv, zp in zip(levels, trend["z_by_peak"])],
})
if pairs:
stat_label = {"dunn": "z", "conover_iman": "t", "nemenyi": "q", "dscf": "q"}[posthoc_method]
diff_label = "Shift (Hodges–Lehmann)" if posthoc_method == "dscf" else "Mean-rank difference"
tables.append({
"key": "posthoc", "title": posthoc_label,
"columns": [{"key": "pair", "label": "Comparison", "type": "string"}, {"key": "diff", "label": diff_label, "type": "number"},
{"key": "stat", "label": stat_label, "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "p_adj", "label": "p (adjusted)", "type": "pvalue"}],
"rows": pairs,
})
how = f"{values['n_perm']} Monte Carlo permutations, seed {seed}" if values.get("n_perm") else "asymptotic"
if alternative == "any":
sym = values["stat_symbol"]
statistics = [{"key": "h", "label": sym, "value": h}, {"key": "df", "label": "df", "value": dof},
{"key": "p", "label": "p", "value": p, "format": "p"}]
apa = f"{sym}({dof}) = {cs.fmt_num(h)}, {cs.fmt_p(p)}, ε² = {cs.fmt_num(epsilon_sq, leading_zero=False)}"
else:
stat_label = {"jonckheere": "J", "cuzick": "T (Cuzick)", "chacko": "H̄ (isotonic)", "mack_wolfe": "A (Mack–Wolfe)"}[test]
statistics = [{"key": "trend_stat", "label": stat_label, "value": values["trend_stat"]}]
if "z" in values:
statistics.append({"key": "z", "label": "z", "value": values["z"]})
statistics += [{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "p_omnibus", "label": "p (omnibus Kruskal–Wallis)", "value": p_omnibus, "format": "p"}]
apa = (f"{label}, H̄ = {cs.fmt_num(values['trend_stat'])}, {cs.fmt_p(p)}" if test == "chacko"
else f"{label}, z = {cs.fmt_num(values['z'])}, {cs.fmt_p(p)}")
effect_sizes = [
{"key": "epsilon_sq", "label": "ε²", "value": epsilon_sq, "method": "T / (n − 1): between-group share of the rank-score variance",
"magnitude": size, "ruleSet": "Cohen (1988)"},
{"key": "eta_sq_h", "label": "η²_H", "value": eta_sq_h, "method": "(T − k + 1) / (n − k)"},
]
if "concordance" in values:
effect_sizes.insert(0, {"key": "concordance", "label": "P(later > earlier)", "value": values["concordance"],
"method": "J / Σ nₐn_b: probability a later group's value exceeds an earlier one's (ties ½); 0.5 = no trend"})
assumptions = [{"key": "shape", "label": "Comparable shapes", "status": "info",
"detail": "With similar shapes the test compares medians; otherwise it compares mean ranks (stochastic dominance)."}]
if alternative != "any":
assumptions.append({"key": "order", "label": "Order fixed in advance", "status": "info",
"detail": f"Order {' < '.join(levels)}" + (f", peak {values['peak']}" if alternative == "umbrella" and trend["peak_known"] else "")
+ ": valid only if chosen before seeing the data."})
if test == "chacko" and used_cal == "asymptotic":
warnings.append("The χ² reference for Chacko's statistic is conservative; choose the permutation p-value for an exact-size test.")
if alternative == "umbrella" and peak is None and calibration == "asymptotic":
warnings.append("With an unknown peak the p-value is calibrated by permutation over all candidate peaks.")
notes = {
"kruskal_wallis": "H is tie-corrected; Dunn's z uses the tie-corrected variance; differences are later − earlier level.",
"van_der_waerden": "Normal scores Φ⁻¹(R/(N+1)) at midranks; T = (N − 1) Σ nⱼāⱼ² / Σ aᵢ² is referred to χ²ₖ₋₁.",
"savage": "Savage scores Σ_{s=N−r+1}^{N} 1/s − 1, averaged over ties; T is referred to χ²ₖ₋₁.",
"mood_median": "Pearson X² on counts above / not above the pooled median (values equal to the median count as not above).",
"jonckheere": "J sums Mann–Whitney counts over ordered pairs (ties ½); the null variance is tie-corrected (Lehmann 1975).",
"cuzick": "T = Σ wᵢRᵢ with group scores w; the variance is the exact permutation variance with ties.",
"chacko": "Mean ranks are made monotone by pool-adjacent-violators before forming the Kruskal–Wallis statistic.",
"mack_wolfe": "A sums Mann–Whitney counts up to the peak and reversed counts after it; null moments of Mack & Wolfe (1981).",
}[test]
if median_custom:
tie_text = {"below": "count as not above", "above": "count as above", "drop": "are left out"}[median_ties]
notes = (f"Pearson X² on counts above / not above the pooled median (values equal to the median {tie_text}"
+ ("; Yates's continuity correction for two groups" if median_yates and k == 2 else "") + ").")
values.update({"median_ties": median_ties, "median_yates": bool(median_yates), "median_n_dropped": mood["n_dropped"]})
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
"method": "nonparam.kruskal_wallis",
"methodVersion": "1.3.0",
"title": label,
"engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
"n": N,
"summary": summary,
"apa": apa,
"statistics": statistics,
"tables": tables,
"effectSizes": effect_sizes,
"assumptions": assumptions,
"warnings": warnings,
"notes": [notes, f"p-value: {how}."],
"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)})],
})
H(2) = 7.99, p = .018, with rank effect size = 0.28. It says at least one group tends to give larger values than another. Like Mann–Whitney, it speaks about medians only if the groups share a shape.
Rank the gaps
ExploreShift one group and watch and the pairwise comparisons change. Then add an outlier: the mean rank moves by only a little, however extreme the value.
BExplorable · Kruskal–Wallis, then Dunn
Once a rank test says the groups differ, which ones differ?
How many of the three pairs will be significant after adjustment?
Adjustment
| Pair | z | Raw p | Adjusted p |
|---|---|---|---|
| A – B | −1.28 | .201 | .402 |
| A – C | −1.51 | .131 | .392 |
| B – C | −0.23 | .816 | .816 |
Commit your prediction above to see the result
Make your prediction to see the result.
Same recipe, different scores
ReadRanks are one choice of score. All of these belong to one family, where you replace ranks with scores and test the same way:
| Rank scores | Replace each rank with | Suits |
|---|---|---|
| Wilcoxon (Kruskal–Wallis) | The rank | Logistic-like shapes, general use |
| Normal (van der Waerden) | The normal quantile of | Near-normal shapes |
| Savage | Exponential scores | Skewed lifetimes, differences in the upper tail |
| Median (Mood) | Above or below the pooled median | Very heavy tails |
Predict the most sensitive
PredictPredict first
Three groups have near-normal shapes, and shift apart in location. On the same data, which test gives the smallest p-value?
Reveal
Van der Waerden: p < .001. Kruskal–Wallis gives p = .002, Savage p = .009 and Mood's median test p = .015. Mood's discards the most information, so it is the least sensitive here.
Choose honestly
ReflectTrying all four and reporting the smallest p-value is a forking path, however legitimate each test is.
Pick the scores from what you know about your outcome's shape before you see the group comparison. If you are unsure, Wilcoxon ranks are a sound default. What do you already know about the shape of your outcome?
Ties in Mood's median test
ReadMood's median test counts values above and not above the pooled median. Values equal to the median have to go somewhere: by default they count as not above, as in the classical test. Values at the median can also put them above or leave them out, and Yates correction adjusts the two-group table. With many values at the median the choice matters, so fix it before looking.
χ²(2) = 8.82, p = .012, ε² = .14
- χ²
- 8.824
- df
- 2
- p
- .012
Effect size
- ε² 0.1352 · medium
- η²_H 0.1013
Plots
View data
| tension | breaks |
|---|---|
| L | 26 |
| L | 30 |
| L | 54 |
| L | 25 |
| L | 70 |
| L | 52 |
| L | 51 |
| L | 26 |
| L | 67 |
| M | 18 |
| M | 21 |
| M | 29 |
| M | 17 |
| M | 12 |
| M | 18 |
| M | 35 |
| M | 30 |
| M | 36 |
| H | 36 |
| H | 21 |
| H | 24 |
| H | 18 |
| H | 10 |
| H | 43 |
| H | 28 |
| H | 15 |
| H | 26 |
| L | 27 |
| L | 14 |
| L | 29 |
| L | 19 |
| L | 29 |
| L | 31 |
| L | 41 |
| L | 20 |
| L | 44 |
| M | 42 |
| M | 26 |
| M | 19 |
| M | 16 |
| M | 39 |
| M | 28 |
| M | 21 |
| M | 39 |
| M | 29 |
| H | 20 |
| H | 21 |
| H | 24 |
| H | 17 |
| H | 13 |
| H | 15 |
| H | 15 |
| H | 16 |
| H | 28 |
Assumptions
- Comparable shapes — With similar shapes the test compares medians; otherwise it compares mean ranks (stochastic dominance).
Descriptives
| tension | n | Median | Mean rank | Above pooled median |
|---|---|---|---|---|
| L | 18 | 29.500 | 36.194 | 12 |
| M | 18 | 27 | 27.333 | 9 |
| H | 18 | 20.500 | 18.972 | 4 |
- Pearson X² on counts above / not above the pooled median (values equal to the median are left out).
- p-value: asymptotic.
The exact R script · R R version 4.5.1 (2025-06-13)
# Kruskal–Wallis test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.kruskal_wallis 1.3.0 · spec fbdfdd2ed923062b
# Dataset: warpbreaks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/warpbreaks.parquet", col_select = c("breaks", "tension")))
n_input <- nrow(df)
df[["tension"]] <- factor(df[["tension"]], levels = c("L", "M", "H")) # stored level order
df <- df[stats::complete.cases(df[c("breaks", "tension")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("breaks", "tension")) # infinite values stop the run (registry/errors.yaml)
# %% 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]
}
# %% Options
y <- "breaks"
g <- "tension"
`%||%` <- function(a, b) if (is.null(a)) b else a
alternative <- "any" %||% "any"
scores <- "median" %||% "wilcoxon"
trend_test <- "jonckheere" %||% "jonckheere"
order_lv <- NULL # the order the alternative refers to (NULL = stored order)
peak <- NULL # umbrella peak level (NULL = unknown)
dose_scores <- FALSE
calibration <- "asymptotic" %||% "asymptotic"
n_perm <- as.integer(9999 %||% 9999)
seed <- 42 # shared Wichmann-Hill stream: Python draws the same permutations
posthoc <- TRUE
posthoc_method <- "dunn" %||% "dunn"
adjust <- "holm" %||% "holm"
# %% Groups, in the order the alternative refers to
present <- levels(df[[g]])
levels_g <- if (!is.null(order_lv)) {
wanted <- as.character(order_lv)
c(wanted[wanted %in% present], present[!present %in% wanted])
} else {
present
}
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
gi <- match(as.character(df[[g]]), levels_g) - 1L
yv <- as.double(df[[y]])
if (length(unique(yv)) < 2) cs_error("CS_E_CONSTANT", column = y) # every rank tied: the test statistic is 0/0
groups <- lapply(0:(k - 1L), function(j) yv[gi == j])
ns <- lengths(groups)
N <- sum(ns)
# %% Omnibus test (linear rank statistic; Wilcoxon scores give the tie-corrected H)
omni_scores <- if (alternative == "any") scores else "wilcoxon"
omni_cal <- if (alternative == "any") calibration else "asymptotic"
omni <- cs_linear_rank(yv, gi, scores = omni_scores, calibration = omni_cal, b = n_perm, seed = seed)
score_t <- omni$t
dof <- k - 1
median_ties <- "drop"
median_yates <- FALSE
median_custom <- omni_scores == "median" && (median_ties != "below" || median_yates) # Stage 12.7 options
if (median_custom && omni_cal != "asymptotic") {
cs_error("CS_E_INVALID_OPTION", option = "The median test's tie rule and Yates correction", allowed = "used with the large-sample p-value", value = omni_cal)
}
if (omni_scores == "median") {
mood <- if (median_custom) cs_mood_median_ext(yv, gi, median_ties, median_yates) else cs_mood_median_chisq(yv, gi)
h <- mood$chisq # classical Pearson X^2 on the above / not-above table
p_omnibus <- if (omni_cal == "asymptotic") mood$p else omni$p_t
} else {
h <- score_t
p_omnibus <- omni$p_t
}
epsilon_sq <- score_t / (N - 1) # between-group share of the score variance (= H / (N - 1))
eta_sq_h <- (score_t - k + 1) / (N - k)
# %% Directional alternatives
test_labels <- c(kruskal_wallis = "Kruskal–Wallis H test", van_der_waerden = "Van der Waerden normal scores test",
savage = "Savage scores test", mood_median = "Mood's median test", jonckheere = "Jonckheere–Terpstra test",
cuzick = "Cuzick trend test", chacko = "Chacko order-restricted test", mack_wolfe = "Mack–Wolfe umbrella test")
symbols <- c(kruskal_wallis = "H", van_der_waerden = "T", savage = "T", mood_median = "χ²")
trend <- NULL
used_cal <- omni_cal
if (alternative == "any") {
test <- c(wilcoxon = "kruskal_wallis", normal = "van_der_waerden", savage = "savage", median = "mood_median")[[scores]]
p <- p_omnibus
} else if (alternative %in% c("increasing", "decreasing")) {
test <- trend_test
used_cal <- calibration
if (trend_test == "jonckheere") {
trend <- cs_jonckheere(yv, gi, alternative, calibration, n_perm, seed)
trend$stat <- trend$j
} else if (trend_test == "cuzick") {
weights <- NULL
if (dose_scores) {
weights <- suppressWarnings(as.double(levels_g))
if (anyNA(weights)) stop(sprintf("The labels of %s must be numbers to use them as doses", g))
}
trend <- cs_cuzick(yv, gi, weights, alternative, calibration, n_perm, seed)
trend$stat <- trend$t
} else if (trend_test == "chacko") {
trend <- cs_chacko(yv, gi, alternative, calibration, n_perm, seed)
trend$stat <- trend$h
trend["z"] <- list(NULL)
} else {
stop(sprintf("unknown trend test '%s'", trend_test))
}
p <- trend$p
} else if (alternative == "umbrella") {
test <- "mack_wolfe"
peak_idx <- if (!is.null(peak) && as.character(peak) %in% levels_g) match(as.character(peak), levels_g) - 1L else NULL
used_cal <- if (!is.null(peak_idx)) calibration else "permutation" # an unknown peak is calibrated jointly
trend <- cs_mack_wolfe(yv, gi, peak_idx, used_cal, n_perm, seed)
trend$stat <- trend$a
p <- trend$p
} else {
stop(sprintf("unknown alternative '%s'", alternative))
}
# %% Post hoc — after the omnibus Wilcoxon-score test only (twins of posthoc.pairwise)
ranks <- rank(yv)
mean_ranks <- vapply(0:(k - 1L), function(j) mean(ranks[gi == j]), numeric(1))
adjust_labels <- c(holm = "Holm", bonferroni = "Bonferroni", hochberg = "Hochberg", BH = "Benjamini–Hochberg", none = "unadjusted")
ph_labels <- c(dunn = "Dunn", conover_iman = "Conover–Iman", nemenyi = "Nemenyi", dscf = "Dwass–Steel–Critchlow–Fligner")
pairs <- list()
posthoc_label <- NULL
if (posthoc && posthoc_method != "none" && k > 2 && alternative == "any" && scores == "wilcoxon") {
rows <- switch(posthoc_method,
conover_iman = cs_conover_iman(groups, levels_g, adjust = adjust)$rows,
nemenyi = cs_nemenyi(groups, levels_g),
dscf = cs_dscf(groups, levels_g),
cs_dunn(groups, levels_g, adjust = adjust)
)
adj_label <- if (posthoc_method %in% c("dunn", "conover_iman")) adjust_labels[[adjust]] else "studentized range"
posthoc_label <- sprintf("%s (%s)", ph_labels[[posthoc_method]], adj_label)
# The twins report earlier - later; keep later - earlier like the Dunn keys of earlier versions.
for (r in seq_len(nrow(rows))) {
pairs[[r]] <- list(pair = paste(rows$b[r], rows$a[r], sep = "-"), diff = -rows$estimate[r], stat = -rows$stat[r],
p = rows$p[r], p_adj = rows$p_adj[r])
}
}
# %% Result
alpha <- 0.05
size <- magnitude(epsilon_sq, c(0.01, 0.06, 0.14))
medians <- vapply(groups, stats::median, numeric(1))
label <- test_labels[[test]]
stat_symbol <- if (test %in% names(symbols)) symbols[[test]] else "H"
values <- list(h = h, df = dof, p = p, p_omnibus = p_omnibus, n = N, k = k, epsilon_sq = epsilon_sq,
eta_sq_h = eta_sq_h, score_t = score_t, test = test, test_label = label, stat_symbol = stat_symbol,
alternative = alternative, calibration = used_cal)
order_text <- paste(levels_g, collapse = " < ")
if (alternative == "any") {
significance <- if (p < alpha) {
sprintf("At least one group tends to differ (%s).", cs_fmt_p(p))
} else {
sprintf("The data are compatible with identical distributions (%s).", cs_fmt_p(p))
}
summary <- sprintf("%s: median %s across %d groups of %s ranged from %.2f to %.2f. %s The effect is %s (ε² = %.2f).",
label, y, k, g, min(medians), max(medians), significance, size, epsilon_sq)
if (!is.null(omni$n_perm)) {
values$n_perm <- omni$n_perm
values$count <- omni$count_t
}
} else {
values$trend_stat <- trend$stat
if (!is.null(trend$z)) values$z <- trend$z
if (!is.null(trend$n_perm)) {
values$n_perm <- trend$n_perm
values$count <- trend$count
}
if (alternative == "umbrella") {
values$peak <- levels_g[trend$peak + 1L]
for (j in seq_len(k)) values[[sprintf("z_peak[%s]", levels_g[j])]] <- trend$z_by_peak[j]
where <- paste0("peak at ", values$peak, if (trend$peak_known) "" else " (estimated; calibrated over all peaks)")
summary <- paste0(sprintf("%s over %s, %s: z = %.2f, %s. ", label, order_text, where, trend$z, cs_fmt_p(p)),
if (p < alpha) "The response rises to the peak and then falls." else "No umbrella pattern is evident.")
} else {
if (test == "jonckheere") {
pairs_total <- 0
for (a in seq_len(k - 1)) for (b in (a + 1):k) pairs_total <- pairs_total + ns[a] * ns[b]
values$concordance <- trend$j / pairs_total
}
direction <- if (alternative == "increasing") "rises" else "falls"
summary <- paste0(sprintf("%s for a %s order %s: %s. ", label, alternative, order_text, cs_fmt_p(p)),
if (p < alpha) sprintf("%s %s across the ordered groups.", y, direction) else sprintf("No %s trend is evident.", alternative),
sprintf(" Omnibus Kruskal–Wallis %s.", cs_fmt_p(p_omnibus)))
}
}
if (length(pairs)) {
summary <- paste(summary, sprintf("%d of %d %s comparisons are significant.",
sum(vapply(pairs, function(r) r$p_adj < alpha, logical(1))), length(pairs), posthoc_label))
values$posthoc_label <- posthoc_label
}
stat_key <- if (posthoc_method == "dunn") "z" else "stat"
for (r in pairs) {
values[[sprintf("%s[%s]", stat_key, r$pair)]] <- r$stat
values[[sprintf("diff[%s]", r$pair)]] <- r$diff
values[[sprintf("p_unadj[%s]", r$pair)]] <- r$p
values[[sprintf("p_adj[%s]", r$pair)]] <- r$p_adj
}
desc_cols <- list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "median", label = "Median", type = "number"), list(key = "mean_rank", label = "Mean rank", type = "number"))
desc_rows <- data.frame(group = levels_g, n = ns, median = medians, mean_rank = mean_ranks)
if (alternative == "any" && scores %in% c("normal", "savage")) {
desc_cols[[length(desc_cols) + 1]] <- list(key = "mean_score", label = "Mean score", type = "number")
desc_rows$mean_score <- omni$mean_score
}
if (alternative == "any" && scores == "median") {
desc_cols[[length(desc_cols) + 1]] <- list(key = "above", label = "Above pooled median", type = "integer")
desc_rows$above <- mood$above
}
if (test == "cuzick") {
desc_cols[[length(desc_cols) + 1]] <- list(key = "weight", label = "Score", type = "number")
desc_rows$weight <- trend$weights
}
if (test == "chacko") {
desc_cols[[length(desc_cols) + 1]] <- list(key = "iso_rank", label = "Isotonic mean rank", type = "number")
desc_rows$iso_rank <- if (alternative == "increasing") trend$iso_ranks else rev(trend$iso_ranks)
}
tables <- list(list(key = "descriptives",
title = if (alternative == "any") "Descriptives" else sprintf("Groups in order (%s)", order_text),
columns = desc_cols, rows = desc_rows))
if (alternative == "umbrella") {
tables[[length(tables) + 1]] <- list(
key = "peaks", title = "Standardized statistic by candidate peak",
columns = list(list(key = "peak", label = "Peak", type = "string"), list(key = "z", label = "z", type = "number")),
rows = data.frame(peak = levels_g, z = trend$z_by_peak)
)
}
if (length(pairs)) {
stat_label <- c(dunn = "z", conover_iman = "t", nemenyi = "q", dscf = "q")[[posthoc_method]]
diff_label <- if (posthoc_method == "dscf") "Shift (Hodges–Lehmann)" else "Mean-rank difference"
tables[[length(tables) + 1]] <- list(
key = "posthoc", title = posthoc_label,
columns = list(list(key = "pair", label = "Comparison", type = "string"), list(key = "diff", label = diff_label, type = "number"),
list(key = "stat", label = stat_label, type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "p_adj", label = "p (adjusted)", type = "pvalue")),
rows = pairs
)
}
how <- if (!is.null(values$n_perm)) sprintf("%d Monte Carlo permutations, seed %d", as.integer(values$n_perm), as.integer(seed)) else "asymptotic"
if (alternative == "any") {
statistics <- list(list(key = "h", label = stat_symbol, value = h), list(key = "df", label = "df", value = dof),
list(key = "p", label = "p", value = p, format = "p"))
apa <- sprintf("%s(%d) = %s, %s, ε² = %s", stat_symbol, as.integer(dof), cs_fmt_num(h), cs_fmt_p(p), cs_fmt_num(epsilon_sq, leading_zero = FALSE))
} else {
stat_label <- c(jonckheere = "J", cuzick = "T (Cuzick)", chacko = "H̄ (isotonic)", mack_wolfe = "A (Mack–Wolfe)")[[test]]
statistics <- list(list(key = "trend_stat", label = stat_label, value = values$trend_stat))
if (!is.null(values$z)) statistics[[length(statistics) + 1]] <- list(key = "z", label = "z", value = values$z)
statistics <- c(statistics, list(list(key = "p", label = "p", value = p, format = "p"),
list(key = "p_omnibus", label = "p (omnibus Kruskal–Wallis)", value = p_omnibus, format = "p")))
apa <- if (test == "chacko") {
sprintf("%s, H̄ = %s, %s", label, cs_fmt_num(values$trend_stat), cs_fmt_p(p))
} else {
sprintf("%s, z = %s, %s", label, cs_fmt_num(values$z), cs_fmt_p(p))
}
}
effect_sizes <- list(
list(key = "epsilon_sq", label = "ε²", value = epsilon_sq, method = "T / (n − 1): between-group share of the rank-score variance",
magnitude = size, ruleSet = "Cohen (1988)"),
list(key = "eta_sq_h", label = "η²_H", value = eta_sq_h, method = "(T − k + 1) / (n − k)")
)
if (!is.null(values$concordance)) {
effect_sizes <- c(list(list(key = "concordance", label = "P(later > earlier)", value = values$concordance,
method = "J / Σ nₐn_b: probability a later group's value exceeds an earlier one's (ties ½); 0.5 = no trend")),
effect_sizes)
}
assumptions <- list(list(key = "shape", label = "Comparable shapes", status = "info",
detail = "With similar shapes the test compares medians; otherwise it compares mean ranks (stochastic dominance)."))
if (alternative != "any") {
assumptions[[2]] <- list(key = "order", label = "Order fixed in advance", status = "info",
detail = paste0("Order ", order_text,
if (alternative == "umbrella" && trend$peak_known) paste0(", peak ", values$peak) else "",
": valid only if chosen before seeing the data."))
}
if (test == "chacko" && used_cal == "asymptotic") {
warnings <- c(warnings, "The χ² reference for Chacko's statistic is conservative; choose the permutation p-value for an exact-size test.")
}
if (alternative == "umbrella" && is.null(peak) && calibration == "asymptotic") {
warnings <- c(warnings, "With an unknown peak the p-value is calibrated by permutation over all candidate peaks.")
}
notes <- c(
kruskal_wallis = "H is tie-corrected; Dunn's z uses the tie-corrected variance; differences are later − earlier level.",
van_der_waerden = "Normal scores Φ⁻¹(R/(N+1)) at midranks; T = (N − 1) Σ nⱼāⱼ² / Σ aᵢ² is referred to χ²ₖ₋₁.",
savage = "Savage scores Σ_{s=N−r+1}^{N} 1/s − 1, averaged over ties; T is referred to χ²ₖ₋₁.",
mood_median = "Pearson X² on counts above / not above the pooled median (values equal to the median count as not above).",
jonckheere = "J sums Mann–Whitney counts over ordered pairs (ties ½); the null variance is tie-corrected (Lehmann 1975).",
cuzick = "T = Σ wᵢRᵢ with group scores w; the variance is the exact permutation variance with ties.",
chacko = "Mean ranks are made monotone by pool-adjacent-violators before forming the Kruskal–Wallis statistic.",
mack_wolfe = "A sums Mann–Whitney counts up to the peak and reversed counts after it; null moments of Mack & Wolfe (1981)."
)[[test]]
if (median_custom) {
tie_text <- c(below = "count as not above", above = "count as above", drop = "are left out")[[median_ties]]
notes <- paste0("Pearson X² on counts above / not above the pooled median (values equal to the median ", tie_text,
if (median_yates && k == 2) "; Yates's continuity correction for two groups" else "", ").")
values$median_ties <- median_ties
values$median_yates <- median_yates
values$median_n_dropped <- mood$n_dropped
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
method = "nonparam.kruskal_wallis",
methodVersion = "1.3.0",
title = label,
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = summary,
apa = apa,
statistics = statistics,
tables = tables,
effectSizes = effect_sizes,
assumptions = assumptions,
warnings = warnings,
notes = list(notes, sprintf("p-value: %s.", how)),
values = values,
charts = 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))))
))
χ²(2) = 8.82, p = .012, ε² = .14
- χ²
- 8.824
- df
- 2
- p
- .012
Effect size
- ε² 0.1352 · medium
- η²_H 0.1013
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Comparable shapes — With similar shapes the test compares medians; otherwise it compares mean ranks (stochastic dominance).
Descriptives
| tension | n | Median | Mean rank | Above pooled median |
|---|---|---|---|---|
| L | 18 | 29.500 | 36.194 | 12 |
| M | 18 | 27 | 27.333 | 9 |
| H | 18 | 20.500 | 18.972 | 4 |
- Pearson X² on counts above / not above the pooled median (values equal to the median are left out).
- p-value: asymptotic.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kruskal–Wallis test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.kruskal_wallis 1.3.0 · spec fbdfdd2ed923062b
# Dataset: warpbreaks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import linear_rank, rank_tests
from codesplash.stats import posthoc as ph
# %% Data
df = pd.read_parquet("tests/parity/fixtures/warpbreaks.parquet", columns=["breaks", "tension"])
n_input = len(df)
df["tension"] = pd.Categorical(df["tension"], categories=["L", "M", "H"]) # stored level order
df = df.dropna(subset=["breaks", "tension"]) # listwise deletion over the analysis columns
df["tension"] = df["tension"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["breaks", "tension"]) # infinite values stop the run (registry/errors.yaml)
# %% 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]
# %% Options
y, g = "breaks", "tension"
alternative = "any" or "any"
scores = "median" or "wilcoxon"
trend_test = "jonckheere" or "jonckheere"
order = None # the order the alternative refers to (None = stored order)
peak = None # umbrella peak level (None = unknown)
dose_scores = False
calibration = "asymptotic" or "asymptotic"
n_perm = int(9999 or 9999)
seed = 42 # shared Wichmann–Hill stream: R draws the same permutations
posthoc = True
posthoc_method = "dunn" or "dunn"
adjust = "holm" or "holm"
# %% Groups, in the order the alternative refers to
present = [str(lv) for lv in df[g].cat.categories]
if order:
wanted = [str(lv) for lv in order]
levels = [lv for lv in wanted if lv in present] + [lv for lv in present if lv not in wanted]
else:
levels = present
k = len(levels)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
gi = df[g].astype(str).map({lv: i for i, lv in enumerate(levels)}).to_numpy(dtype=np.int64)
yv = df[y].to_numpy(dtype=float)
if len(np.unique(yv)) < 2: # every rank tied: the test statistic is 0/0
cs.cs_error("CS_E_CONSTANT", column=y)
groups = [yv[gi == j] for j in range(k)]
ns = np.array([len(x) for x in groups])
N = int(ns.sum())
# %% Omnibus test (linear rank statistic; Wilcoxon scores give the tie-corrected H)
omni_scores = scores if alternative == "any" else "wilcoxon"
omni_cal = calibration if alternative == "any" else "asymptotic"
omni = linear_rank.linear_rank(yv, gi, scores=omni_scores, calibration=omni_cal, b=n_perm, seed=seed)
score_t = omni["t"]
dof = k - 1
median_ties, median_yates = "drop", False
median_custom = omni_scores == "median" and (median_ties != "below" or median_yates) # Stage 12.7 options
if median_custom and omni_cal != "asymptotic":
cs.cs_error("CS_E_INVALID_OPTION", option="The median test's tie rule and Yates correction", allowed="used with the large-sample p-value", value=omni_cal)
if omni_scores == "median":
if median_custom:
from codesplash.stats import stat_options as csopt
mood = csopt.mood_median_ext(yv, gi, median_ties, median_yates)
else:
mood = linear_rank.mood_median_chisq(yv, gi)
h = mood["chisq"] # classical Pearson X² on the above / not-above table
p_omnibus = mood["p"] if omni_cal == "asymptotic" else omni["p_t"]
else:
h = score_t
p_omnibus = omni["p_t"]
epsilon_sq = score_t / (N - 1) # between-group share of the score variance (= H / (N − 1))
eta_sq_h = (score_t - k + 1) / (N - k)
# %% Directional alternatives
TEST_LABELS = {
"kruskal_wallis": "Kruskal–Wallis H test", "van_der_waerden": "Van der Waerden normal scores test",
"savage": "Savage scores test", "mood_median": "Mood's median test", "jonckheere": "Jonckheere–Terpstra test",
"cuzick": "Cuzick trend test", "chacko": "Chacko order-restricted test", "mack_wolfe": "Mack–Wolfe umbrella test",
}
SYMBOLS = {"kruskal_wallis": "H", "van_der_waerden": "T", "savage": "T", "mood_median": "χ²"}
trend = None
used_cal = omni_cal
if alternative == "any":
test = {"wilcoxon": "kruskal_wallis", "normal": "van_der_waerden", "savage": "savage", "median": "mood_median"}[scores]
p = p_omnibus
elif alternative in ("increasing", "decreasing"):
test = trend_test
used_cal = calibration
if trend_test == "jonckheere":
trend = rank_tests.jonckheere(yv, gi, alternative, calibration, n_perm, seed)
trend["stat"] = trend["j"]
elif trend_test == "cuzick":
weights = None
if dose_scores:
try:
weights = [float(lv) for lv in levels]
except ValueError:
raise ValueError(f"The labels of {g} must be numbers to use them as doses") from None
trend = rank_tests.cuzick(yv, gi, weights, alternative, calibration, n_perm, seed)
trend["stat"] = trend["t"]
elif trend_test == "chacko":
trend = rank_tests.chacko(yv, gi, alternative, calibration, n_perm, seed)
trend["stat"] = trend["h"]
trend["z"] = None
else:
raise ValueError(f"unknown trend test {trend_test!r}")
p = trend["p"]
elif alternative == "umbrella":
test = "mack_wolfe"
peak_idx = levels.index(str(peak)) if peak is not None and str(peak) in levels else None
used_cal = calibration if peak_idx is not None else "permutation" # an unknown peak is calibrated jointly
trend = rank_tests.mack_wolfe(yv, gi, peak_idx, used_cal, n_perm, seed)
trend["stat"] = trend["a"]
p = trend["p"]
else:
raise ValueError(f"unknown alternative {alternative!r}")
# %% Post hoc — after the omnibus Wilcoxon-score test only (twins of posthoc.pairwise)
ranks = stats.rankdata(yv)
mean_ranks = [float(ranks[gi == j].mean()) for j in range(k)]
ADJUST_LABELS = {"holm": "Holm", "bonferroni": "Bonferroni", "hochberg": "Hochberg", "BH": "Benjamini–Hochberg", "none": "unadjusted"}
PH_LABELS = {"dunn": "Dunn", "conover_iman": "Conover–Iman", "nemenyi": "Nemenyi", "dscf": "Dwass–Steel–Critchlow–Fligner"}
pairs = []
posthoc_label = None
if posthoc and posthoc_method != "none" and k > 2 and alternative == "any" and scores == "wilcoxon":
if posthoc_method == "conover_iman":
rows, _ = ph.conover_iman(groups, levels, adjust=adjust)
elif posthoc_method == "nemenyi":
rows = ph.nemenyi(groups, levels)
elif posthoc_method == "dscf":
rows = ph.dscf(groups, levels)
else:
rows = ph.dunn(groups, levels, adjust=adjust)
adj_label = ADJUST_LABELS[adjust] if posthoc_method in ("dunn", "conover_iman") else "studentized range"
posthoc_label = f"{PH_LABELS[posthoc_method]} ({adj_label})"
# The twins report earlier − later; keep later − earlier like the Dunn keys of earlier versions.
for r in rows:
pairs.append({"pair": f"{r['b']}-{r['a']}", "diff": -float(r["estimate"]), "stat": -float(r["stat"]),
"p": float(r["p"]), "p_adj": float(r["p_adj"])})
# %% Result
alpha = 0.05
size = magnitude(epsilon_sq, (0.01, 0.06, 0.14))
medians = [float(np.median(x)) for x in groups]
label = TEST_LABELS[test]
values = {"h": h, "df": float(dof), "p": p, "p_omnibus": p_omnibus, "n": N, "k": k, "epsilon_sq": epsilon_sq,
"eta_sq_h": eta_sq_h, "score_t": score_t, "test": test, "test_label": label,
"stat_symbol": SYMBOLS.get(test, "H"), "alternative": alternative, "calibration": used_cal}
if alternative == "any":
significance = (f"At least one group tends to differ ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with identical distributions ({cs.fmt_p(p)}).")
summary = (f"{label}: median {y} across {k} groups of {g} ranged from {min(medians):.2f} to {max(medians):.2f}. "
f"{significance} The effect is {size} (ε² = {epsilon_sq:.2f}).")
if omni["n_perm"]:
values.update(n_perm=omni["n_perm"], count=omni["count_t"])
else:
values["trend_stat"] = float(trend["stat"])
if trend.get("z") is not None:
values["z"] = float(trend["z"])
if trend["n_perm"]:
values.update(n_perm=trend["n_perm"], count=trend["count"])
order_text = " < ".join(levels)
if alternative == "umbrella":
values["peak"] = levels[trend["peak"]]
for lv, zp in zip(levels, trend["z_by_peak"]):
values[f"z_peak[{lv}]"] = float(zp)
where = f"peak at {values['peak']}" + ("" if trend["peak_known"] else " (estimated; calibrated over all peaks)")
summary = (f"{label} over {order_text}, {where}: z = {trend['z']:.2f}, {cs.fmt_p(p)}. "
+ ("The response rises to the peak and then falls." if p < alpha else "No umbrella pattern is evident."))
else:
if test == "jonckheere":
pairs_total = sum(int(ns[a] * ns[b]) for a in range(k) for b in range(a + 1, k))
values["concordance"] = float(trend["j"] / pairs_total)
direction = "rises" if alternative == "increasing" else "falls"
summary = (f"{label} for a {alternative} order {order_text}: {cs.fmt_p(p)}. "
+ (f"{y} {direction} across the ordered groups." if p < alpha else f"No {alternative} trend is evident.")
+ f" Omnibus Kruskal–Wallis {cs.fmt_p(p_omnibus)}.")
if pairs:
summary += f" {sum(r['p_adj'] < alpha for r in pairs)} of {len(pairs)} {posthoc_label} comparisons are significant."
values["posthoc_label"] = posthoc_label
stat_key = "z" if posthoc_method == "dunn" else "stat"
for r in pairs:
values.update({f"{stat_key}[{r['pair']}]": r["stat"], f"diff[{r['pair']}]": r["diff"], f"p_unadj[{r['pair']}]": r["p"],
f"p_adj[{r['pair']}]": r["p_adj"]})
desc_cols = [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "median", "label": "Median", "type": "number"}, {"key": "mean_rank", "label": "Mean rank", "type": "number"}]
desc_rows = [{"group": lv, "n": int(n), "median": m, "mean_rank": r} for lv, n, m, r in zip(levels, ns, medians, mean_ranks)]
if alternative == "any" and scores in ("normal", "savage"):
desc_cols.append({"key": "mean_score", "label": "Mean score", "type": "number"})
for row, ms in zip(desc_rows, omni["mean_score"]):
row["mean_score"] = float(ms)
if alternative == "any" and scores == "median":
desc_cols.append({"key": "above", "label": "Above pooled median", "type": "integer"})
for row, a in zip(desc_rows, mood["above"]):
row["above"] = int(a)
if test == "cuzick":
desc_cols.append({"key": "weight", "label": "Score", "type": "number"})
for row, w in zip(desc_rows, trend["weights"]):
row["weight"] = float(w)
if test == "chacko":
desc_cols.append({"key": "iso_rank", "label": "Isotonic mean rank", "type": "number"})
iso = trend["iso_ranks"] if alternative == "increasing" else trend["iso_ranks"][::-1]
for row, r in zip(desc_rows, iso):
row["iso_rank"] = float(r)
tables = [{"key": "descriptives", "title": "Descriptives" if alternative == "any" else f"Groups in order ({' < '.join(levels)})",
"columns": desc_cols, "rows": desc_rows}]
if alternative == "umbrella":
tables.append({
"key": "peaks", "title": "Standardized statistic by candidate peak",
"columns": [{"key": "peak", "label": "Peak", "type": "string"}, {"key": "z", "label": "z", "type": "number"}],
"rows": [{"peak": lv, "z": float(zp)} for lv, zp in zip(levels, trend["z_by_peak"])],
})
if pairs:
stat_label = {"dunn": "z", "conover_iman": "t", "nemenyi": "q", "dscf": "q"}[posthoc_method]
diff_label = "Shift (Hodges–Lehmann)" if posthoc_method == "dscf" else "Mean-rank difference"
tables.append({
"key": "posthoc", "title": posthoc_label,
"columns": [{"key": "pair", "label": "Comparison", "type": "string"}, {"key": "diff", "label": diff_label, "type": "number"},
{"key": "stat", "label": stat_label, "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "p_adj", "label": "p (adjusted)", "type": "pvalue"}],
"rows": pairs,
})
how = f"{values['n_perm']} Monte Carlo permutations, seed {seed}" if values.get("n_perm") else "asymptotic"
if alternative == "any":
sym = values["stat_symbol"]
statistics = [{"key": "h", "label": sym, "value": h}, {"key": "df", "label": "df", "value": dof},
{"key": "p", "label": "p", "value": p, "format": "p"}]
apa = f"{sym}({dof}) = {cs.fmt_num(h)}, {cs.fmt_p(p)}, ε² = {cs.fmt_num(epsilon_sq, leading_zero=False)}"
else:
stat_label = {"jonckheere": "J", "cuzick": "T (Cuzick)", "chacko": "H̄ (isotonic)", "mack_wolfe": "A (Mack–Wolfe)"}[test]
statistics = [{"key": "trend_stat", "label": stat_label, "value": values["trend_stat"]}]
if "z" in values:
statistics.append({"key": "z", "label": "z", "value": values["z"]})
statistics += [{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "p_omnibus", "label": "p (omnibus Kruskal–Wallis)", "value": p_omnibus, "format": "p"}]
apa = (f"{label}, H̄ = {cs.fmt_num(values['trend_stat'])}, {cs.fmt_p(p)}" if test == "chacko"
else f"{label}, z = {cs.fmt_num(values['z'])}, {cs.fmt_p(p)}")
effect_sizes = [
{"key": "epsilon_sq", "label": "ε²", "value": epsilon_sq, "method": "T / (n − 1): between-group share of the rank-score variance",
"magnitude": size, "ruleSet": "Cohen (1988)"},
{"key": "eta_sq_h", "label": "η²_H", "value": eta_sq_h, "method": "(T − k + 1) / (n − k)"},
]
if "concordance" in values:
effect_sizes.insert(0, {"key": "concordance", "label": "P(later > earlier)", "value": values["concordance"],
"method": "J / Σ nₐn_b: probability a later group's value exceeds an earlier one's (ties ½); 0.5 = no trend"})
assumptions = [{"key": "shape", "label": "Comparable shapes", "status": "info",
"detail": "With similar shapes the test compares medians; otherwise it compares mean ranks (stochastic dominance)."}]
if alternative != "any":
assumptions.append({"key": "order", "label": "Order fixed in advance", "status": "info",
"detail": f"Order {' < '.join(levels)}" + (f", peak {values['peak']}" if alternative == "umbrella" and trend["peak_known"] else "")
+ ": valid only if chosen before seeing the data."})
if test == "chacko" and used_cal == "asymptotic":
warnings.append("The χ² reference for Chacko's statistic is conservative; choose the permutation p-value for an exact-size test.")
if alternative == "umbrella" and peak is None and calibration == "asymptotic":
warnings.append("With an unknown peak the p-value is calibrated by permutation over all candidate peaks.")
notes = {
"kruskal_wallis": "H is tie-corrected; Dunn's z uses the tie-corrected variance; differences are later − earlier level.",
"van_der_waerden": "Normal scores Φ⁻¹(R/(N+1)) at midranks; T = (N − 1) Σ nⱼāⱼ² / Σ aᵢ² is referred to χ²ₖ₋₁.",
"savage": "Savage scores Σ_{s=N−r+1}^{N} 1/s − 1, averaged over ties; T is referred to χ²ₖ₋₁.",
"mood_median": "Pearson X² on counts above / not above the pooled median (values equal to the median count as not above).",
"jonckheere": "J sums Mann–Whitney counts over ordered pairs (ties ½); the null variance is tie-corrected (Lehmann 1975).",
"cuzick": "T = Σ wᵢRᵢ with group scores w; the variance is the exact permutation variance with ties.",
"chacko": "Mean ranks are made monotone by pool-adjacent-violators before forming the Kruskal–Wallis statistic.",
"mack_wolfe": "A sums Mann–Whitney counts up to the peak and reversed counts after it; null moments of Mack & Wolfe (1981).",
}[test]
if median_custom:
tie_text = {"below": "count as not above", "above": "count as above", "drop": "are left out"}[median_ties]
notes = (f"Pearson X² on counts above / not above the pooled median (values equal to the median {tie_text}"
+ ("; Yates's continuity correction for two groups" if median_yates and k == 2 else "") + ").")
values.update({"median_ties": median_ties, "median_yates": bool(median_yates), "median_n_dropped": mood["n_dropped"]})
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
"method": "nonparam.kruskal_wallis",
"methodVersion": "1.3.0",
"title": label,
"engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
"n": N,
"summary": summary,
"apa": apa,
"statistics": statistics,
"tables": tables,
"effectSizes": effect_sizes,
"assumptions": assumptions,
"warnings": warnings,
"notes": [notes, f"p-value: {how}."],
"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)})],
})
Mood's test targets equal population medians, and its χ² p-value needs adequate expected counts in the table. An exact or permutation p-value for it assumes something stronger: that all groups share one distribution under the null.
Check your understanding
CheckpointCheck yourself
You run Kruskal–Wallis with only two groups. How does it relate to Mann–Whitney?
Show the answer
Answer: a
For two groups equals the squared z of the rank sum test.
Check yourself
With 30 observations in total, what mean rank would every group have if the groups were perfectly alike?
Show the answer
Answer: 15.5
(N + 1) / 2 = 31 / 2 = 15.5.
Check yourself
Your outcome is time to failure: strongly right-skewed, and you expect groups to differ most among the long-lived units. Which rank scores fit best?
Show the answer
Answer: b
Savage scores suit exponential-like data and are the uncensored form of the log-rank test.
Check yourself
In warpbreaks, 4 values equal the pooled median. What happens to them when "Values at the median" is set to Leave out?
Show the answer
Answer: b
Leave out drops values equal to the median before building the table (scipy's ties="ignore"); the result reports how many were left out.
Do it in CodeSplash
In the appPick the Rank scores in the Kruskal–Wallis dialog before you run it. Set p-value to Monte Carlo permutation (seeded) if your sample is small or has many ties, and keep Pairwise comparisons on for the follow-ups.
import pandas as pd
from scipy import stats
df = pd.read_csv("plantgrowth.csv")
groups = [g["weight"] for _, g in df.groupby("group")]
print(stats.kruskal(*groups))
print(stats.median_test(*groups)) # Mood's median testkruskal.test(weight ~ group, data = PlantGrowth)
# install.packages("coin")
coin::normal_test(weight ~ group, data = PlantGrowth) # van der Waerden
coin::savage_test(weight ~ group, data = PlantGrowth)
coin::median_test(weight ~ group, data = PlantGrowth) # Mood's scoresRecap
Recap- Kruskal–Wallis is a one-way ANOVA on ranks.
- Mood, van der Waerden and Savage use other scores suited to other shapes.
- Choose the scores from what you know about the outcome, not from the p-values.
Concepts in this lesson