Skip to content

Mann–Whitney: what a rank test really tests

The rank sum test compares how often one group beats the other. It is not a test of medians, and that distinction changes how you report it.

Applied ~11 min10 steps

What runs in CodeSplash

You will be able to

  • Compute U from pairwise wins between two groups
  • Interpret the probability of superiority and the Hodges–Lehmann shift
  • Explain why Mann–Whitney is not a test of medians

Read first

01

From values to wins

Read

Take every pair of one value from each group and ask which is larger. A win counts 1, a tie counts ½. The total for group 1 is UMann–Whitney testCompares two independent groups by how often a value from one beats a value from the other, using ranks.:

U=∑i∑j[1(xi>yj)+12 1(xi=yj)]U = \sum_{i}\sum_{j} \left[\mathbb 1(x_i > y_j) + \tfrac12\, \mathbb 1(x_i = y_j)\right]

Divide by the number of pairs and you have the probability of superiority: how often a random value from one group beats a random value from the other. Half means no tendency either way.

Some texts, including the edition-2 reference's formula, count group 1's losses instead; that U equals n1n2n_1 n_2 minus this one. SciPy's mannwhitneyu(x, y) and R's shifted rank sum report the orientation above. The two-sided p-value is the same either way, so check the orientation before reading a direction.

02

Guess the probability

Predict

Predict first

ToothGrowth compares 30 animals on orange juice with 30 on ascorbic acid. Their medians are 22.7 and 16.5.

Pick one animal from each group at random. How likely is the OJ animal to have the longer teeth?

Make your guess between 0 and 1 probability OJ beats VC, then reveal.

Reveal

U = 575.5 out of 900 pairs, so the probability is 0.64.

03

See ranks at work

Explore

Drag a point far from the others. The mean moves with it; its rank barely changes. That is why rank tests shrug off outliers, and also why they ignore how far apart values are.

BExplorable · What ranks throw away

What changes when a test uses ranks instead of the values?

If the largest value became ten times larger, what would the Mann–Whitney p-value do?

How sure?
1.00
12
0
valuesranks
Testp
t test on values.009
Mann–Whitney.007
t test on ranks.005

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

04

Read the result

Read
Mann–Whitney U testRecorded · Python and R agreeRecorded 2026-11-21 · 15 values compared
R

U = 575.5, p = .064, r = .28

U
575.50
p
.064
Hodges–Lehmann shift (OJ − VC)
4

Effect size

  • Rank-biserial r 0.2789 · small
  • Probability of superiority 0.6394

Plots

len by suppHow do groups compare in shape, summary and individual observations at once?
View data
supplen
VC4.200
VC11.500
VC7.300
VC5.800
VC6.400
VC10
VC11.200
VC11.200
VC5.200
VC7
VC16.500
VC16.500
VC15.200
VC17.300
VC22.500
VC17.300
VC13.600
VC14.500
VC18.800
VC15.500
VC23.600
VC18.500
VC33.900
VC25.500
VC26.400
VC32.500
VC26.700
VC21.500
VC23.300
VC29.500
OJ15.200
OJ21.500
OJ17.600
OJ9.700
OJ14.500
OJ10
OJ8.200
OJ9.400
OJ16.500
OJ9.700
OJ19.700
OJ23.300
OJ23.600
OJ26.400
OJ20
OJ25.200
OJ25.800
OJ21.200
OJ14.500
OJ27.300
OJ25.500
OJ26.400
OJ22.400
OJ24.500
OJ24.800
OJ30.900
OJ26.400
OJ27.300
OJ29.400
OJ23

Assumptions

  • Comparable shapes — With similar distribution shapes the test compares medians; otherwise it compares P(first > second).

Descriptives

suppnMedianQ1Q3Mean rank
OJ3022.70015.52525.72534.683
VC3016.50011.20023.10026.317
  • Normal approximation with tie correction and continuity correction; alternative: two-sided.
  • Hodges–Lehmann shift 4, 95% Moses interval [-0.1, 8.5].
The exact R script · R R version 4.5.1 (2025-06-13)
# Mann–Whitney U test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.mann_whitney 1.3.0 · spec 81df0c13fc07b2b5
# Dataset: toothgrowth (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/toothgrowth.parquet", col_select = c("len", "supp")))
n_input <- nrow(df)
df[["supp"]] <- factor(df[["supp"]], levels = c("OJ", "VC"))  # stored level order
df <- df[stats::complete.cases(df[c("len", "supp")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("len", "supp"))  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
  # Benchmark label for an effect size (rule set named in the result)
  if (is.null(x) || !is.finite(x)) return("undetermined")
  labels[findInterval(abs(x), cuts) + 1]
}

# %% Test
y <- "len"
g <- "supp"
levels_g <- levels(df[[g]])
if (length(levels_g) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(levels_g))
x1 <- df[[y]][df[[g]] == levels_g[1]]
x2 <- df[[y]][df[[g]] == levels_g[2]]
if (length(unique(c(x1, x2))) < 2) cs_error("CS_E_CONSTANT", column = y)  # every rank tied: the test statistic is 0/0
n1 <- length(x1)
n2 <- length(x2)
alternative <- "two-sided"
correct <- TRUE  # continuity correction (pinned)
method <- "asymptotic"
ties <- length(unique(c(x1, x2))) < n1 + n2
if (method == "exact" && ties) {
  # Exact null distributions assume no ties: use the tie-corrected normal approximation.
  method <- "asymptotic"
  warnings <- c(warnings, "Tied values: the exact p-value is unavailable, so the tie-corrected normal approximation was used.")
}

res <- wilcox.test(x1, x2, alternative = sub("-", ".", alternative, fixed = TRUE), exact = method == "exact", correct = correct)
u <- unname(res$statistic)  # W = U for the first group
p <- res$p.value
perm_extra <- list()
if (method == "permutation") {  # Stage 12.7 option: Monte Carlo permutation p (shared Wichmann-Hill stream)
  perm <- cs_rank_sum_perm_p(x1, x2, alternative, as.integer(9999), as.integer(1))
  p <- perm$p
  perm_extra <- list(n_perm = perm$b, perm_count = perm$count)
}
r_rb <- 2 * u / (n1 * n2) - 1  # rank-biserial correlation; positive = first group tends higher
cles <- u / (n1 * n2)  # P(first > second) + 1/2 P(tie)
hl <- median(outer(x1, x2, "-"))  # Hodges-Lehmann shift (first - second)
# Moses (1953) distribution-free 95% interval for the shift; its normal-approximation SE,
# (upper - lower) / (2 z_0.975), is what the lenses below use (normal reference, df = NULL).
hlci <- cs_hodges_lehmann_ci(x1, x2, 0.95)
lens_kind <- "none"
if (is.null(lens_kind)) lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") lens <- cs_lens(lens_kind, hl, hlci$se, NULL, NULL, NULL, 0.05)
med1 <- median(x1)
med2 <- median(x2)

# %% Result
alpha <- 0.05
size <- magnitude(r_rb, c(0.1, 0.3, 0.5))
significance <- if (p < alpha) {
  sprintf("The groups differ significantly (%s).", cs_fmt_p(p))
} else {
  sprintf("The data are compatible with no difference in location (%s).", cs_fmt_p(p))
}
summary <- sprintf(
  "%s tended to be %s in %s (median %.2f) than in %s (median %.2f). %s The rank-biserial correlation is %s (r = %.2f); a randomly chosen %s value exceeds a %s value with probability %.2f.",
  y, if (r_rb > 0) "higher" else "lower", levels_g[1], med1, levels_g[2], med2, significance, size, r_rb, levels_g[1], levels_g[2], cles
)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s) on the Hodges–Lehmann shift: %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
ranks <- rank(c(x1, x2))
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
  method = "nonparam.mann_whitney",
  methodVersion = "1.3.0",
  title = "Mann–Whitney U test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n1 + n2,
  summary = summary,
  apa = sprintf("U = %s, %s, r = %s", format(u), cs_fmt_p(p), cs_fmt_num(r_rb, leading_zero = FALSE)),
  statistics = c(list(
    list(key = "u", label = "U", value = u),
    list(key = "p", label = "p", value = p, format = "p"),
    list(key = "hl_shift", label = sprintf("Hodges–Lehmann shift (%s − %s)", levels_g[1], levels_g[2]), value = hl)
  ), if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list()),
  tables = list(list(
    key = "descriptives", title = "Descriptives",
    columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
                   list(key = "median", label = "Median", type = "number"), list(key = "q1", label = "Q1", type = "number"),
                   list(key = "q3", label = "Q3", type = "number"), list(key = "mean_rank", label = "Mean rank", type = "number")),
    rows = data.frame(group = levels_g, n = c(n1, n2), median = c(med1, med2),
                      q1 = c(quantile(x1, 0.25, type = 7), quantile(x2, 0.25, type = 7)),
                      q3 = c(quantile(x1, 0.75, type = 7), quantile(x2, 0.75, type = 7)),
                      mean_rank = c(mean(ranks[seq_len(n1)]), mean(ranks[n1 + seq_len(n2)])), row.names = NULL)
  )),
  effectSizes = list(
    list(key = "rank_biserial", label = "Rank-biserial r", value = r_rb, method = "2U / (n1 n2) − 1", magnitude = size, ruleSet = "Cohen (1988), r"),
    list(key = "cles", label = "Probability of superiority", value = cles, method = "U / (n1 n2)")
  ),
  assumptions = list(list(key = "shape", label = "Comparable shapes", status = "info",
                          detail = "With similar distribution shapes the test compares medians; otherwise it compares P(first > second).")),
  warnings = warnings,
  notes = c(list(sprintf("%s; alternative: %s.", if (method == "exact") "Exact" else if (method == "permutation") sprintf("Permutation p-value (%d permutations of the group labels, (count + 1) / (B + 1))", perm_extra$n_perm) else paste0("Normal approximation with tie correction", if (correct) " and continuity correction" else ""), alternative),
                 sprintf("Hodges–Lehmann shift %.3g, 95%% Moses interval [%.3g, %.3g].", hl, hlci$ci_low, hlci$ci_high)),
            if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the 90%% normal-approximation interval for the shift (SE from the Moses interval).",
                                             lens$lens_ci_low, lens$lens_ci_high)) else list()),
  values = c(list(u = u, p = p, n_1 = n1, n_2 = n2, rank_biserial = r_rb, cles = cles, hl_shift = hl,
                median_1 = med1, median_2 = med2, method = method, level_1 = as.character(levels_g[1]), level_2 = as.character(levels_g[2]),
                hl_ci_low = hlci$ci_low, hl_ci_high = hlci$ci_high, hl_se = hlci$se), lens, perm_extra),
  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(df[[g]])))))
))
Python

U = 575.5, p = .064, r = .28

U
575.50
p
.064
Hodges–Lehmann shift (OJ − VC)
4.000

Effect size

  • Rank-biserial r 0.2789 · small
  • Probability of superiority 0.6394

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Comparable shapes — With similar distribution shapes the test compares medians; otherwise it compares P(first > second).

Descriptives

suppnMedianQ1Q3Mean rank
OJ3022.70015.52525.72534.683
VC3016.50011.20023.10026.317
  • Normal approximation with tie correction and continuity correction; alternative: two-sided.
  • Hodges–Lehmann shift 4, 95% Moses interval [-0.1, 8.5].
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mann–Whitney U test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.mann_whitney 1.3.0 · spec 81df0c13fc07b2b5
# Dataset: toothgrowth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import means as csm
from codesplash.stats import rank_tests

# %% Data
df = pd.read_parquet("tests/parity/fixtures/toothgrowth.parquet", columns=["len", "supp"])
n_input = len(df)
df["supp"] = pd.Categorical(df["supp"], categories=["OJ", "VC"])  # stored level order
df = df.dropna(subset=["len", "supp"])  # listwise deletion over the analysis columns
df["supp"] = df["supp"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["len", "supp"])  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
    """Benchmark label for an effect size (rule set named in the result)."""
    if x is None or not np.isfinite(x):
        return "undetermined"
    for cut, label in zip(cuts, labels):
        if abs(x) < cut:
            return label
    return labels[-1]

# %% Test
y, g = "len", "supp"
levels = list(df[g].cat.categories)
if len(levels) != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
x1 = df.loc[df[g] == levels[0], y].to_numpy(dtype=float)
x2 = df.loc[df[g] == levels[1], y].to_numpy(dtype=float)
if len(np.unique(np.concatenate([x1, x2]))) < 2:  # every rank tied: the test statistic is 0/0
    cs.cs_error("CS_E_CONSTANT", column=y)
n1, n2 = len(x1), len(x2)
alternative = "two-sided"
correct = True  # continuity correction (pinned; both engines default to True)
method = "asymptotic"
ties = len(np.unique(np.concatenate([x1, x2]))) < n1 + n2
if method == "exact" and ties:
    # Exact null distributions assume no ties (R falls back too): use the tie-corrected normal approximation.
    method = "asymptotic"
    warnings.append("Tied values: the exact p-value is unavailable, so the tie-corrected normal approximation was used.")

res = stats.mannwhitneyu(x1, x2, alternative=alternative, use_continuity=correct,
                         method="asymptotic" if method == "permutation" else method)
u, p = float(res.statistic), float(res.pvalue)  # U for the first group (= R's W)
perm_extra = {}
if method == "permutation":  # Stage 12.7 option: Monte Carlo permutation p (shared Wichmann–Hill stream)
    from codesplash.stats import stat_options as csopt
    perm = csopt.rank_sum_perm_p(x1, x2, alternative, int(9999), int(1))
    p = perm["p"]
    perm_extra = {"n_perm": perm["b"], "perm_count": perm["count"]}
p_desc = ("Exact" if method == "exact"
          else f"Permutation p-value ({perm_extra['n_perm']} permutations of the group labels, (count + 1) / (B + 1))" if method == "permutation"
          else "Normal approximation with tie correction" + (" and continuity correction" if correct else ""))
r_rb = 2 * u / (n1 * n2) - 1  # rank-biserial correlation; positive = first group tends higher
cles = u / (n1 * n2)  # P(first > second) + ½ P(tie)
hl = float(np.median(np.subtract.outer(x1, x2)))  # Hodges–Lehmann shift (first − second)
# Moses (1953) distribution-free 95% interval for the shift; its normal-approximation SE,
# (upper − lower) / (2 z₀.₉₇₅), is what the lenses below use (normal reference, df = None).
hlci = rank_tests.hodges_lehmann_ci(x1, x2, 0.95)
lens_kind = "none" or "none"
lens = None
if lens_kind != "none":
    lens = csm.lens(lens_kind, hl, hlci["se"], None, None, None, 0.05)
med1, med2 = float(np.median(x1)), float(np.median(x2))

# %% Result
alpha = 0.05
size = magnitude(r_rb, (0.1, 0.3, 0.5))
significance = (
    f"The groups differ significantly ({cs.fmt_p(p)})." if p < alpha
    else f"The data are compatible with no difference in location ({cs.fmt_p(p)})."
)
summary = (
    f"{y} tended to be {'higher' if r_rb > 0 else 'lower'} in {levels[0]} (median {med1:.2f}) than in {levels[1]} "
    f"(median {med2:.2f}). {significance} The rank-biserial correlation is {size} (r = {r_rb:.2f}); a randomly chosen "
    f"{levels[0]} value exceeds a {levels[1]} value with probability {cles:.2f}."
)
if lens:
    summary += f" Lens ({lens_kind.replace('_', ' ')}) on the Hodges–Lehmann shift: {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
    "method": "nonparam.mann_whitney",
    "methodVersion": "1.3.0",
    "title": "Mann–Whitney U test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n1 + n2,
    "summary": summary,
    "apa": f"U = {u:g}, {cs.fmt_p(p)}, r = {cs.fmt_num(r_rb, leading_zero=False)}",
    "statistics": [
        {"key": "u", "label": "U", "value": u},
        {"key": "p", "label": "p", "value": p, "format": "p"},
        {"key": "hl_shift", "label": f"Hodges–Lehmann shift ({levels[0]} − {levels[1]})", "value": hl},
    ] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else []),
    "tables": [{
        "key": "descriptives", "title": "Descriptives",
        "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                    {"key": "median", "label": "Median", "type": "number"}, {"key": "q1", "label": "Q1", "type": "number"},
                    {"key": "q3", "label": "Q3", "type": "number"}, {"key": "mean_rank", "label": "Mean rank", "type": "number"}],
        "rows": [
            {"group": str(lv), "n": len(x), "median": float(np.median(x)), "q1": float(np.quantile(x, 0.25)), "q3": float(np.quantile(x, 0.75)),
             "mean_rank": float(stats.rankdata(np.concatenate([x1, x2]))[i * n1:(n1 if i == 0 else n1 + n2)].mean())}
            for i, (lv, x) in enumerate(zip(levels, (x1, x2)))
        ],
    }],
    "effectSizes": [
        {"key": "rank_biserial", "label": "Rank-biserial r", "value": r_rb, "method": "2U / (n1 n2) − 1", "magnitude": size, "ruleSet": "Cohen (1988), r"},
        {"key": "cles", "label": "Probability of superiority", "value": cles, "method": "U / (n1 n2)"},
    ],
    "assumptions": [{"key": "shape", "label": "Comparable shapes", "status": "info",
                     "detail": "With similar distribution shapes the test compares medians; otherwise it compares P(first > second)."}],
    "warnings": warnings,
    "notes": [f"{p_desc}; alternative: {alternative}.",
              f"Hodges–Lehmann shift {hl:.3g}, 95% Moses interval [{hlci['ci_low']:.3g}, {hlci['ci_high']:.3g}]."]
             + ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the 90% normal-approximation interval for the shift "
                 "(SE from the Moses interval)."] if lens else []),
    "values": {
        "u": u, "p": p, "n_1": n1, "n_2": n2, "rank_biserial": r_rb, "cles": cles, "hl_shift": hl,
        "median_1": med1, "median_2": med2, "method": method, "level_1": str(levels[0]), "level_2": str(levels[1]),
        "hl_ci_low": hlci["ci_low"], "hl_ci_high": hlci["ci_high"], "hl_se": hlci["se"],
        **(lens or {}),
        **perm_extra,
    },
    "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=[str(x) for x in df[g].cat.categories])})],
})

U = 575.5, p = .064. The rank-biserial correlation is 0.28, which is twice the probability of superiority minus 1.

The Hodges–Lehmann shift of 4 units (95% CI −0.100 to 8.50) is the median of all pairwise differences. It is an effect in the outcome's own units.

05

Not a test of medians

Read

With identical shapes, a shift in location does move the medians, and the test then reads as a median comparison. Without that assumption, say what the test does measure: the tendency of one group to exceed the other.

06

Exact or approximate

Reflect

With 6 values per group and no ties, CodeSplash can count every arrangement: U = 2, p = .009.

With ties or larger samples it uses the normal approximation with a continuity correction, and it tells you when an exact request has to fall back.

Before you trust the next rank test you run, ask yourself: how many ties does this column have, and would you notice?

07

A permutation p-value

Read

With ties, the exact Mann–Whitney p is unavailable and the normal approximation is used. The Permutation p-value is a third choice: it shuffles the group labels thousands of times, recomputes U each time and counts how often it is at least as far from n1n2/2 as the observed U. It holds at any sample size, ties included.

Mann–Whitney U testRecorded · Python and R agreeRecorded 2026-11-21 · 17 values compared
R

U = 575.5, p = .079, r = .28

U
575.50
p
.079
Hodges–Lehmann shift (OJ − VC)
4

Effect size

  • Rank-biserial r 0.2789 · small
  • Probability of superiority 0.6394

Plots

len by suppHow do groups compare in shape, summary and individual observations at once?
View data
supplen
VC4.200
VC11.500
VC7.300
VC5.800
VC6.400
VC10
VC11.200
VC11.200
VC5.200
VC7
VC16.500
VC16.500
VC15.200
VC17.300
VC22.500
VC17.300
VC13.600
VC14.500
VC18.800
VC15.500
VC23.600
VC18.500
VC33.900
VC25.500
VC26.400
VC32.500
VC26.700
VC21.500
VC23.300
VC29.500
OJ15.200
OJ21.500
OJ17.600
OJ9.700
OJ14.500
OJ10
OJ8.200
OJ9.400
OJ16.500
OJ9.700
OJ19.700
OJ23.300
OJ23.600
OJ26.400
OJ20
OJ25.200
OJ25.800
OJ21.200
OJ14.500
OJ27.300
OJ25.500
OJ26.400
OJ22.400
OJ24.500
OJ24.800
OJ30.900
OJ26.400
OJ27.300
OJ29.400
OJ23

Assumptions

  • Comparable shapes — With similar distribution shapes the test compares medians; otherwise it compares P(first > second).

Descriptives

suppnMedianQ1Q3Mean rank
OJ3022.70015.52525.72534.683
VC3016.50011.20023.10026.317
  • Permutation p-value (999 permutations of the group labels, (count + 1) / (B + 1)); alternative: two-sided.
  • Hodges–Lehmann shift 4, 95% Moses interval [-0.1, 8.5].
The exact R script · R R version 4.5.1 (2025-06-13)
# Mann–Whitney U test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.mann_whitney 1.3.0 · spec 257cfd2e140b61f1
# Dataset: toothgrowth (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/toothgrowth.parquet", col_select = c("len", "supp")))
n_input <- nrow(df)
df[["supp"]] <- factor(df[["supp"]], levels = c("OJ", "VC"))  # stored level order
df <- df[stats::complete.cases(df[c("len", "supp")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("len", "supp"))  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
  # Benchmark label for an effect size (rule set named in the result)
  if (is.null(x) || !is.finite(x)) return("undetermined")
  labels[findInterval(abs(x), cuts) + 1]
}

# %% Test
y <- "len"
g <- "supp"
levels_g <- levels(df[[g]])
if (length(levels_g) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(levels_g))
x1 <- df[[y]][df[[g]] == levels_g[1]]
x2 <- df[[y]][df[[g]] == levels_g[2]]
if (length(unique(c(x1, x2))) < 2) cs_error("CS_E_CONSTANT", column = y)  # every rank tied: the test statistic is 0/0
n1 <- length(x1)
n2 <- length(x2)
alternative <- "two-sided"
correct <- TRUE  # continuity correction (pinned)
method <- "permutation"
ties <- length(unique(c(x1, x2))) < n1 + n2
if (method == "exact" && ties) {
  # Exact null distributions assume no ties: use the tie-corrected normal approximation.
  method <- "asymptotic"
  warnings <- c(warnings, "Tied values: the exact p-value is unavailable, so the tie-corrected normal approximation was used.")
}

res <- wilcox.test(x1, x2, alternative = sub("-", ".", alternative, fixed = TRUE), exact = method == "exact", correct = correct)
u <- unname(res$statistic)  # W = U for the first group
p <- res$p.value
perm_extra <- list()
if (method == "permutation") {  # Stage 12.7 option: Monte Carlo permutation p (shared Wichmann-Hill stream)
  perm <- cs_rank_sum_perm_p(x1, x2, alternative, as.integer(999), as.integer(1))
  p <- perm$p
  perm_extra <- list(n_perm = perm$b, perm_count = perm$count)
}
r_rb <- 2 * u / (n1 * n2) - 1  # rank-biserial correlation; positive = first group tends higher
cles <- u / (n1 * n2)  # P(first > second) + 1/2 P(tie)
hl <- median(outer(x1, x2, "-"))  # Hodges-Lehmann shift (first - second)
# Moses (1953) distribution-free 95% interval for the shift; its normal-approximation SE,
# (upper - lower) / (2 z_0.975), is what the lenses below use (normal reference, df = NULL).
hlci <- cs_hodges_lehmann_ci(x1, x2, 0.95)
lens_kind <- "none"
if (is.null(lens_kind)) lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") lens <- cs_lens(lens_kind, hl, hlci$se, NULL, NULL, NULL, 0.05)
med1 <- median(x1)
med2 <- median(x2)

# %% Result
alpha <- 0.05
size <- magnitude(r_rb, c(0.1, 0.3, 0.5))
significance <- if (p < alpha) {
  sprintf("The groups differ significantly (%s).", cs_fmt_p(p))
} else {
  sprintf("The data are compatible with no difference in location (%s).", cs_fmt_p(p))
}
summary <- sprintf(
  "%s tended to be %s in %s (median %.2f) than in %s (median %.2f). %s The rank-biserial correlation is %s (r = %.2f); a randomly chosen %s value exceeds a %s value with probability %.2f.",
  y, if (r_rb > 0) "higher" else "lower", levels_g[1], med1, levels_g[2], med2, significance, size, r_rb, levels_g[1], levels_g[2], cles
)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s) on the Hodges–Lehmann shift: %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
ranks <- rank(c(x1, x2))
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
  method = "nonparam.mann_whitney",
  methodVersion = "1.3.0",
  title = "Mann–Whitney U test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n1 + n2,
  summary = summary,
  apa = sprintf("U = %s, %s, r = %s", format(u), cs_fmt_p(p), cs_fmt_num(r_rb, leading_zero = FALSE)),
  statistics = c(list(
    list(key = "u", label = "U", value = u),
    list(key = "p", label = "p", value = p, format = "p"),
    list(key = "hl_shift", label = sprintf("Hodges–Lehmann shift (%s − %s)", levels_g[1], levels_g[2]), value = hl)
  ), if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list()),
  tables = list(list(
    key = "descriptives", title = "Descriptives",
    columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
                   list(key = "median", label = "Median", type = "number"), list(key = "q1", label = "Q1", type = "number"),
                   list(key = "q3", label = "Q3", type = "number"), list(key = "mean_rank", label = "Mean rank", type = "number")),
    rows = data.frame(group = levels_g, n = c(n1, n2), median = c(med1, med2),
                      q1 = c(quantile(x1, 0.25, type = 7), quantile(x2, 0.25, type = 7)),
                      q3 = c(quantile(x1, 0.75, type = 7), quantile(x2, 0.75, type = 7)),
                      mean_rank = c(mean(ranks[seq_len(n1)]), mean(ranks[n1 + seq_len(n2)])), row.names = NULL)
  )),
  effectSizes = list(
    list(key = "rank_biserial", label = "Rank-biserial r", value = r_rb, method = "2U / (n1 n2) − 1", magnitude = size, ruleSet = "Cohen (1988), r"),
    list(key = "cles", label = "Probability of superiority", value = cles, method = "U / (n1 n2)")
  ),
  assumptions = list(list(key = "shape", label = "Comparable shapes", status = "info",
                          detail = "With similar distribution shapes the test compares medians; otherwise it compares P(first > second).")),
  warnings = warnings,
  notes = c(list(sprintf("%s; alternative: %s.", if (method == "exact") "Exact" else if (method == "permutation") sprintf("Permutation p-value (%d permutations of the group labels, (count + 1) / (B + 1))", perm_extra$n_perm) else paste0("Normal approximation with tie correction", if (correct) " and continuity correction" else ""), alternative),
                 sprintf("Hodges–Lehmann shift %.3g, 95%% Moses interval [%.3g, %.3g].", hl, hlci$ci_low, hlci$ci_high)),
            if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the 90%% normal-approximation interval for the shift (SE from the Moses interval).",
                                             lens$lens_ci_low, lens$lens_ci_high)) else list()),
  values = c(list(u = u, p = p, n_1 = n1, n_2 = n2, rank_biserial = r_rb, cles = cles, hl_shift = hl,
                median_1 = med1, median_2 = med2, method = method, level_1 = as.character(levels_g[1]), level_2 = as.character(levels_g[2]),
                hl_ci_low = hlci$ci_low, hl_ci_high = hlci$ci_high, hl_se = hlci$se), lens, perm_extra),
  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(df[[g]])))))
))
Python

U = 575.5, p = .079, r = .28

U
575.50
p
.079
Hodges–Lehmann shift (OJ − VC)
4.000

Effect size

  • Rank-biserial r 0.2789 · small
  • Probability of superiority 0.6394

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Comparable shapes — With similar distribution shapes the test compares medians; otherwise it compares P(first > second).

Descriptives

suppnMedianQ1Q3Mean rank
OJ3022.70015.52525.72534.683
VC3016.50011.20023.10026.317
  • Permutation p-value (999 permutations of the group labels, (count + 1) / (B + 1)); alternative: two-sided.
  • Hodges–Lehmann shift 4, 95% Moses interval [-0.1, 8.5].
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mann–Whitney U test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.mann_whitney 1.3.0 · spec 257cfd2e140b61f1
# Dataset: toothgrowth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import means as csm
from codesplash.stats import rank_tests

# %% Data
df = pd.read_parquet("tests/parity/fixtures/toothgrowth.parquet", columns=["len", "supp"])
n_input = len(df)
df["supp"] = pd.Categorical(df["supp"], categories=["OJ", "VC"])  # stored level order
df = df.dropna(subset=["len", "supp"])  # listwise deletion over the analysis columns
df["supp"] = df["supp"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["len", "supp"])  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
    """Benchmark label for an effect size (rule set named in the result)."""
    if x is None or not np.isfinite(x):
        return "undetermined"
    for cut, label in zip(cuts, labels):
        if abs(x) < cut:
            return label
    return labels[-1]

# %% Test
y, g = "len", "supp"
levels = list(df[g].cat.categories)
if len(levels) != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
x1 = df.loc[df[g] == levels[0], y].to_numpy(dtype=float)
x2 = df.loc[df[g] == levels[1], y].to_numpy(dtype=float)
if len(np.unique(np.concatenate([x1, x2]))) < 2:  # every rank tied: the test statistic is 0/0
    cs.cs_error("CS_E_CONSTANT", column=y)
n1, n2 = len(x1), len(x2)
alternative = "two-sided"
correct = True  # continuity correction (pinned; both engines default to True)
method = "permutation"
ties = len(np.unique(np.concatenate([x1, x2]))) < n1 + n2
if method == "exact" and ties:
    # Exact null distributions assume no ties (R falls back too): use the tie-corrected normal approximation.
    method = "asymptotic"
    warnings.append("Tied values: the exact p-value is unavailable, so the tie-corrected normal approximation was used.")

res = stats.mannwhitneyu(x1, x2, alternative=alternative, use_continuity=correct,
                         method="asymptotic" if method == "permutation" else method)
u, p = float(res.statistic), float(res.pvalue)  # U for the first group (= R's W)
perm_extra = {}
if method == "permutation":  # Stage 12.7 option: Monte Carlo permutation p (shared Wichmann–Hill stream)
    from codesplash.stats import stat_options as csopt
    perm = csopt.rank_sum_perm_p(x1, x2, alternative, int(999), int(1))
    p = perm["p"]
    perm_extra = {"n_perm": perm["b"], "perm_count": perm["count"]}
p_desc = ("Exact" if method == "exact"
          else f"Permutation p-value ({perm_extra['n_perm']} permutations of the group labels, (count + 1) / (B + 1))" if method == "permutation"
          else "Normal approximation with tie correction" + (" and continuity correction" if correct else ""))
r_rb = 2 * u / (n1 * n2) - 1  # rank-biserial correlation; positive = first group tends higher
cles = u / (n1 * n2)  # P(first > second) + ½ P(tie)
hl = float(np.median(np.subtract.outer(x1, x2)))  # Hodges–Lehmann shift (first − second)
# Moses (1953) distribution-free 95% interval for the shift; its normal-approximation SE,
# (upper − lower) / (2 z₀.₉₇₅), is what the lenses below use (normal reference, df = None).
hlci = rank_tests.hodges_lehmann_ci(x1, x2, 0.95)
lens_kind = "none" or "none"
lens = None
if lens_kind != "none":
    lens = csm.lens(lens_kind, hl, hlci["se"], None, None, None, 0.05)
med1, med2 = float(np.median(x1)), float(np.median(x2))

# %% Result
alpha = 0.05
size = magnitude(r_rb, (0.1, 0.3, 0.5))
significance = (
    f"The groups differ significantly ({cs.fmt_p(p)})." if p < alpha
    else f"The data are compatible with no difference in location ({cs.fmt_p(p)})."
)
summary = (
    f"{y} tended to be {'higher' if r_rb > 0 else 'lower'} in {levels[0]} (median {med1:.2f}) than in {levels[1]} "
    f"(median {med2:.2f}). {significance} The rank-biserial correlation is {size} (r = {r_rb:.2f}); a randomly chosen "
    f"{levels[0]} value exceeds a {levels[1]} value with probability {cles:.2f}."
)
if lens:
    summary += f" Lens ({lens_kind.replace('_', ' ')}) on the Hodges–Lehmann shift: {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
    "method": "nonparam.mann_whitney",
    "methodVersion": "1.3.0",
    "title": "Mann–Whitney U test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n1 + n2,
    "summary": summary,
    "apa": f"U = {u:g}, {cs.fmt_p(p)}, r = {cs.fmt_num(r_rb, leading_zero=False)}",
    "statistics": [
        {"key": "u", "label": "U", "value": u},
        {"key": "p", "label": "p", "value": p, "format": "p"},
        {"key": "hl_shift", "label": f"Hodges–Lehmann shift ({levels[0]} − {levels[1]})", "value": hl},
    ] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else []),
    "tables": [{
        "key": "descriptives", "title": "Descriptives",
        "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                    {"key": "median", "label": "Median", "type": "number"}, {"key": "q1", "label": "Q1", "type": "number"},
                    {"key": "q3", "label": "Q3", "type": "number"}, {"key": "mean_rank", "label": "Mean rank", "type": "number"}],
        "rows": [
            {"group": str(lv), "n": len(x), "median": float(np.median(x)), "q1": float(np.quantile(x, 0.25)), "q3": float(np.quantile(x, 0.75)),
             "mean_rank": float(stats.rankdata(np.concatenate([x1, x2]))[i * n1:(n1 if i == 0 else n1 + n2)].mean())}
            for i, (lv, x) in enumerate(zip(levels, (x1, x2)))
        ],
    }],
    "effectSizes": [
        {"key": "rank_biserial", "label": "Rank-biserial r", "value": r_rb, "method": "2U / (n1 n2) − 1", "magnitude": size, "ruleSet": "Cohen (1988), r"},
        {"key": "cles", "label": "Probability of superiority", "value": cles, "method": "U / (n1 n2)"},
    ],
    "assumptions": [{"key": "shape", "label": "Comparable shapes", "status": "info",
                     "detail": "With similar distribution shapes the test compares medians; otherwise it compares P(first > second)."}],
    "warnings": warnings,
    "notes": [f"{p_desc}; alternative: {alternative}.",
              f"Hodges–Lehmann shift {hl:.3g}, 95% Moses interval [{hlci['ci_low']:.3g}, {hlci['ci_high']:.3g}]."]
             + ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the 90% normal-approximation interval for the shift "
                 "(SE from the Moses interval)."] if lens else []),
    "values": {
        "u": u, "p": p, "n_1": n1, "n_2": n2, "rank_biserial": r_rb, "cles": cles, "hl_shift": hl,
        "median_1": med1, "median_2": med2, "method": method, "level_1": str(levels[0]), "level_2": str(levels[1]),
        "hl_ci_low": hlci["ci_low"], "hl_ci_high": hlci["ci_high"], "hl_se": hlci["se"],
        **(lens or {}),
        **perm_extra,
    },
    "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=[str(x) for x in df[g].cat.categories])})],
})
08

Check your understanding

Checkpoint

Check yourself

Group A is 3, 5. Group B is 1, 4. Count A's wins across all pairs to get U for group A.

Show the answer

Answer: 3

3 beats 1 but not 4; 5 beats both. That is 3 wins out of 4 pairs, so U = 3 and the probability of superiority is 3/4.

Check yourself

A Mann–Whitney comparison gives a probability of superiority of 0.70. Which statement fits?

Show the answer

Answer: b

The probability of superiority is about pairs of values. It says nothing direct about medians and is not a probability about hypotheses.

Check yourself

Two groups have identical medians but one is far more spread out. Mann–Whitney gives a small p-value. What is the safe conclusion?

Show the answer

Answer: c

The test responds to any difference that changes who beats whom. Different shapes can do that with equal medians.

Check yourself

A permutation p-value from 999 shuffles is reported as 0.001. What does that tell you?

Show the answer

Answer: b

The permutation p is (count + 1) / (B + 1). With B = 999 the smallest possible value is 0.001; more shuffles would let it go lower.

09

Do it in CodeSplash

In the app

Choose an Outcome and two Groups. Set p-value to exact for small tables without ties. The card reports the shift and its interval alongside p, so you can report an effect.

Python
import pandas as pd
from scipy import stats

df = pd.read_csv("toothgrowth.csv")
oj = df.loc[df["supp"] == "OJ", "len"]
vc = df.loc[df["supp"] == "VC", "len"]
print(stats.mannwhitneyu(oj, vc, alternative="two-sided", method="asymptotic"))
R
df <- read.csv("toothgrowth.csv")
df$supp <- factor(df$supp, levels = c("OJ", "VC"))
wilcox.test(len ~ supp, data = df, exact = FALSE, conf.int = TRUE)
10

Recap

Recap
  • U counts wins across every pair; divide by the number of pairs for the probability of superiority.
  • Report that probability or the Hodges–Lehmann shift with its interval.
  • Call it a median test only if the two distributions have the same shape.

Concepts in this lesson