BCompare groups · nonparam.kruskal_wallis
Kruskal–Wallis test
Do three or more independent groups differ in location (without assuming normality)?
Rank-based one-way comparison (tie-corrected H) with ε² and η²_H, followed by Dunn's pairwise z-tests with Holm adjustment. Other rank scores give the van der Waerden, Savage and Mood median tests; ordered alternatives give the Jonckheere–Terpstra, Cuzick and Chacko trend tests and the Mack–Wolfe umbrella test.
A real result
Example “Plantgrowth”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
H(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.
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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Plantgrowthplantgrowth · group: group · outcome: weight
- Tieswarpbreaks · group: tension · outcome: breaks
- Missing values no posthocairquality · group: month_f · outcome: Ozone
- Mood median guidec3_rank3 · group: group · outcome: value
- Mood median tieswarpbreaks · group: tension · outcome: breaks
- Mood median ties abovewarpbreaks · group: tension · outcome: breaks
- Mood median ties dropwarpbreaks · group: tension · outcome: breaks
- Mood median yates 2groupstoothgrowth · group: supp · outcome: len
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- More than two independent groups: one-way ANOVA, Kruskal–Wallis · Statistics Guide · B — Compare groups
- Post hoc: Tukey HSD, Dunnett, Holm, Games–Howell · Statistics Guide · B — Compare groups
- Multiple comparisons · Statistics Guide · Additional considerations
- Non-parametric alternatives · Statistics Guide · Additional considerations
What you need
- Outcomenumeric · 1 column
- The numeric variable you are analyzing.
- Groupscategorical / boolean · 1 column · 2–30 levels
- The column whose levels define the groups to compare.
Choices you make
hypothesis
- Alternative hypothesisdefault any
Any difference (omnibus), or an ordered pattern across the group order you set: increasing, decreasing or umbrella.
- Some groups differ (omnibus)(default) — Any difference in location among the groups.
- Increases across the group order — An ordered (trend) alternative, e.g. rising doses; fix the order before seeing the data.
- Decreases across the group order — An ordered alternative, values falling across the groups; fix the order before seeing the data.
- Rises to a peak, then falls (umbrella) — Mack–Wolfe: up to a peak group, then down; the peak may be known or unknown.
- Trend testdefault jonckheere
Test for an ordered trend across the groups. Jonckheere–Terpstra is the classic choice.
- Jonckheere–Terpstra(default) — Counts how often a later group's value beats an earlier group's, over all ordered pairs.
- Cuzick (ranks × group scores) — Correlates pooled ranks with group scores 1..k, or with numeric doses.
- Chacko (order-restricted Kruskal–Wallis) — Kruskal–Wallis on isotonic (monotone) mean ranks; calibrate by permutation.
- Group orderdefault —
The order the alternative refers to (first = lowest dose). Fix it before looking at the data.
- Peak groupdefault —
Leave empty when the peak is unknown: the largest standardized statistic is then calibrated by permutation.
- Use numeric group labels as dosesdefault off
Cuzick scores from the labels (0, 10, 50 mg …) instead of 1..k; unequal spacing changes the alternative.
statistics
- Rank scoresdefault wilcoxon
Scores given to the ranks: Wilcoxon ranks (KW), normal scores, Savage scores, or above/below the median (Mood).
- Wilcoxon ranks (Kruskal–Wallis H)(default) — Pooled ranks; the standard choice for differences in location.
- Normal scores (van der Waerden) — Φ⁻¹(rank / (N + 1)): most powerful for normal-shaped shifts; extremes weigh more.
- Savage (exponential) scores — Emphasizes the upper tail; suited to lifetimes and exponential-type shifts.
- Above / below the pooled median (Mood's median test) — Counts values above the pooled median per group; robust but loses information.
- Values at the mediandefault below
Where values equal to the pooled median go. With many ties at the median the choice can change the result, so fix it before looking.
- Count as below (default)(default) — Values equal to the pooled median count as not above it, as in the classical test and scipy's default.
- Count as above — Values equal to the pooled median count as above it.
- Leave out — Values equal to the pooled median are left out of the table; the test uses the remaining rows.
- Yates correction (two groups)default off
Applies Yates's continuity correction to the 2 × 2 table when there are two groups, as scipy's median_test does by default.
options
- p-valuedefault asymptotic
How the p-value is computed: a large-sample formula, or by permutation or simulation (slower, fewer assumptions).
- Asymptotic (χ² or normal)(default) — Large-sample reference distribution; fast.
- Monte Carlo permutation (seeded) — Relabels the groups many times; exact up to Monte Carlo error and the same in Python and R.
- Monte Carlo permutationsdefault 9999
More permutations give a steadier p-value; the umbrella test with an unknown peak always permutes.
posthoc
- Pairwise comparisonsdefault on
After the overall test, compare each pair of groups, with p-values adjusted for the number of comparisons.
- Pairwise testdefault dunn
Follow-up comparisons of every pair of groups after the Kruskal–Wallis test.
- Dunn(default) — z on mean ranks from the joint ranking (tie-corrected), then the adjustment below.
- Conover–Iman — t on mean ranks with the Kruskal–Wallis residual variance; more powerful than Dunn.
- Nemenyi — Mean ranks against the studentized range; controls the familywise error by itself.
- Dwass–Steel–Critchlow–Fligner — Each pair ranked on its own (Wilcoxon), studentized range; robust to unequal spreads.
- None — Report only the omnibus test.
- Adjustmentdefault holm
How the pairwise p-values are adjusted for multiplicity (Nemenyi and DSCF adjust through the studentized range).
- Holm(default) — Step-down familywise control; uniformly better than Bonferroni.
- Bonferroni — Multiplies each p by the number of tests; the plainest and strictest control, best for a few comparisons.
- Hochberg — Step-up familywise control; valid for independent or positively dependent tests.
- Benjamini–Hochberg (FDR) — Controls the false discovery rate instead of the familywise error.
- None — Reports raw p-values; use it for one planned comparison, or say plainly that the results are exploratory.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Comparable shapes
Independent observations
Order fixed in advance
Ordered and umbrella alternatives are valid only when the order (and peak) were chosen before seeing the data.
What it reports
- Tests: Differences among groups (ranks)
- h
- The rank-based counterpart of one-way ANOVA, comparing mean ranks across three or more independent groups.
- df
- How much independent information is left to estimate variability after fitting the model.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_omnibus
- How surprising your data would be if the null hypothesis were true, as a probability.
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- epsilon_sq
- A bias-adjusted variance-explained measure; for Kruskal–Wallis it is computed from the ranks.
- eta_sq_h
- The share of total variance explained by an effect in ANOVA; biased upward in small samples.
- score_t
- An estimate divided by its standard error, compared with a t distribution.
- test
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- test_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- stat_symbol
- Symbol of the omnibus statistic: H (Kruskal–Wallis), T (van der Waerden or Savage scores) or χ² (Mood's median test).
- alternative
- Which pattern the test looked for: any difference, an increasing or decreasing trend across the group order, or an umbrella peak.
- calibration
- Each p-value comes from a reference distribution, a simulation of the null, or an exact count: this column says which.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Per group, level or term: median_ties, median_yates, median_n_dropped, z[<later>-<earlier>], stat[<later>-<earlier>], diff[<later>-<earlier>], p_unadj[…], p_adj[…], posthoc_label, trend_stat, z, concordance, peak, n_perm, count, z_peak[<level>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, statsmodels, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Twin implementation (codesplash.stats.linear_rank / rank_tests ↔ cs_linear_rank / cs_*); H equals scipy.stats.kruskal and kruskal.test, normal and Savage scores equal coin's normal_test and savage_test (ties.method = 'average-scores' for Savage).
- Jonckheere–Terpstra uses the exact tie-corrected null variance (Lehmann 1975); DescTools and some PMCMRplus versions use the no-ties variance, so their asymptotic p differs slightly with ties.
- Monte Carlo p-values use the shared Wichmann–Hill stream: Python and R relabel identically and report the same p = (count + 1)/(B + 1).
The exact script CodeSplash ran for example “Plantgrowth” · 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)})],
})
The exact script CodeSplash ran for example “Plantgrowth” · 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))))
))
Sources
- Kruskal, W. H., & Wallis, W. A. (1952). Use of ranks in one-criterion variance analysis. JASA, 47, 583–621.
- Dunn, O. J. (1964). Multiple comparisons using rank sums. Technometrics, 6, 241–252.
- Tomczak, M., & Tomczak, E. (2014). The need to report effect size estimates revisited. Trends in Sport Sciences, 1, 19–25.
- Hájek, J., Šidák, Z., & Sen, P. K. (1999). Theory of Rank Tests (2nd ed.). Academic Press.
- Mood, A. M. (1950). Introduction to the Theory of Statistics. McGraw-Hill (median test).
- van der Waerden, B. L. (1952). Order tests for the two-sample problem and their power. Indagationes Mathematicae, 14, 453–458.
- Savage, I. R. (1956). Contributions to the theory of rank order statistics — the two-sample case. Ann. Math. Statist., 27, 590–615.
- Jonckheere, A. R. (1954). A distribution-free k-sample test against ordered alternatives. Biometrika, 41, 133–145.
- Cuzick, J. (1985). A Wilcoxon-type test for trend. Statistics in Medicine, 4, 87–90.
- Chacko, V. J. (1963). Testing homogeneity against ordered alternatives. Ann. Math. Statist., 34, 945–956.
- Mack, G. A., & Wolfe, D. A. (1981). K-sample rank tests for umbrella alternatives. JASA, 76, 175–181.
- Hollander, M., Wolfe, D. A., & Chicken, E. (2014). Nonparametric Statistical Methods (3rd ed.). Wiley.
From the CodeSplash method registry · nonparam.kruskal_wallis v1.3.0.