Skip to content

BCompare groups · nonparam.wilcoxon_signed_rank

Wilcoxon signed-rank test

Did paired measurements change systematically (without assuming normal differences)?

Rank-based test of paired differences (zeros dropped). Reports V (sum of positive ranks), the matched-pairs rank-biserial correlation and the Hodges–Lehmann pseudo-median.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Sleep ties zero”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Wilcoxon signed-rank testRecorded · Python and R agreeRecorded 2026-11-17 · 8 values compared
R

V = 0, p = .009, r = −1.00

V (sum of positive ranks)
0
p
.009
Pseudo-median difference
−1.400

Effect size

  • Matched-pairs rank-biserial r −1 · large

Plots

drug1 and drug2 per rowHow did each subject change across conditions or time points?
View data
MeasurementRowValue
drug110.7000
drug12−1.600
drug13−0.2000
drug14−1.200
drug15−0.1000
drug163.400
drug173.700
drug180.8000
drug190
drug1102
drug211.900
drug220.8000
drug231.100
drug240.1000
drug25−0.1000
drug264.400
drug275.500
drug281.600
drug294.600
drug2103.400

Assumptions

  • Symmetric differences — The test assumes the differences are symmetric around their median; otherwise read it as a sign-like test.

Paired differences

PairsZero differencesdrug1 > drug2drug1 < drug2Median difference
10109−1.300
  • Differences rounded to 10 decimals, then zero differences dropped; normal approximation with tie correction; alternative: two-sided.
Python

V = 0, p = .009, r = −1.00

V (sum of positive ranks)
0
p
.009
Pseudo-median difference
−1.400

Effect size

  • Matched-pairs rank-biserial r −1 · large

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

Assumptions

  • Symmetric differences — The test assumes the differences are symmetric around their median; otherwise read it as a sign-like test.

Paired differences

PairsZero differencesdrug1 > drug2drug1 < drug2Median difference
10109−1.300
  • Differences rounded to 10 decimals, then zero differences dropped; normal approximation with tie correction; alternative: two-sided.

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

  • Sleep ties zerosleep_wide · x: drug1 · y: drug2
  • Exactscores · x: after · y: before
  • No correctioniris · x: Sepal.Width · y: Petal.Length
  • Float noise differencessta_float_noise · x: after · y: before

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • One sample (continuous): one-sample t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
  • Paired (continuous): paired t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
  • Non-parametric alternatives · Statistics Guide · Additional considerations

What you need

First measurementnumeric · 1 column
The difference is first − second.
Second measurementnumeric · 1 column
The second measurement on the same subjects (leave empty for a one-sample test).

Choices you make

hypothesis

Alternative hypothesisdefault two-sided

Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.

  • Differences centered away from 0(default) — Tests for differences centered away from 0 in either direction; keep it unless you fixed a direction before seeing the data.
  • First tends higher — Tests only for the first measure tending higher; pick it only if you fixed this direction before seeing the data.
  • First tends lower — Tests only for the first measure tending lower; pick it only if you fixed this direction before seeing the data.

options

p-valuedefault asymptotic

Normal approximation (handles ties) or the exact distribution (small samples, no ties or zero differences).

  • Normal approximation (tie-corrected)(default) — Uses a tie-corrected normal approximation; fine with moderate samples, ties or zeros.
  • Exact (no ties or zeros only) — Uses the exact null distribution; for small samples with no ties or zeros.

Advanced

Continuity correctiondefault on

Apply a continuity correction to the normal approximation; p-values become slightly more conservative.

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.

  • Symmetric differences

    • If violated → Sign test — Uses only the signs of the differences, so it does not need symmetric differences. Changes the question: Tests the median difference.
  • Pairs belong togetherNot checked from data: state why it holds

What it reports

  • Tests: Systematic paired change
v
Ranks the sizes of paired differences, then compares the positive ranks with the negative ones.
p
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.
n_zero
How many independent units the analysis used; it sets precision and power.
rank_biserial
An effect size for Mann–Whitney and Wilcoxon tests; the share of favorable minus unfavorable pairs.
hl_estimate
The median of all pairwise differences between groups; the shift estimate behind rank tests.
median_diff
The middle value when the data are sorted; half the values lie on each side.
method
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • scipy reports min(W+, W−) for two-sided tests; the template reports V = W+ (R's statistic) in both engines.
  • Paired differences are rounded to 10 decimals (rint(d·10¹⁰)/10¹⁰, the same arithmetic in both engines; the reference's R code uses round(x − y, 10)) before zeros and ties are found, so floating-point noise such as 0.1 + 0.2 − 0.3 is not a difference. Data measured below 1e-10 should be rescaled first.
Python

The exact script CodeSplash ran for example “Sleep ties zero” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Wilcoxon signed-rank test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.wilcoxon_signed_rank 2.0.1 · spec b8e0aaa0496d3252
# Dataset: sleep_wide (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

# %% Data
df = pd.read_parquet("tests/parity/fixtures/sleep_wide.parquet", columns=["drug1", "drug2"])
n_input = len(df)
df = df.dropna(subset=["drug1", "drug2"])  # listwise deletion over the analysis columns
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, ["drug1", "drug2"])  # 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
a, b = "drug1", "drug2"
d = df[a].to_numpy(dtype=float) - df[b].to_numpy(dtype=float)
d = np.rint(d * 1e10) / 1e10  # rounded to 10 decimals so floating-point noise is not a difference (same in R)
n_zero = int((d == 0).sum())
nz = d[d != 0]  # zero differences are dropped (R's default; scipy zero_method="wilcox")
n = len(nz)
if n == 0:
    raise ValueError("All paired differences are zero.")
alternative = "two-sided"
correct = True  # continuity correction (pinned)
method = "asymptotic"
ranks = stats.rankdata(np.abs(nz))
ties = len(np.unique(np.abs(nz))) < n
if method == "exact" and (ties or n_zero):
    method = "asymptotic"
    warnings.append("Ties or zero differences: the exact p-value is unavailable, so the tie-corrected normal approximation was used.")

res = stats.wilcoxon(nz, zero_method="wilcox", correction=correct, alternative=alternative, method=method)
p = float(res.pvalue)
v = float(ranks[nz > 0].sum())  # V = sum of positive ranks (R's statistic; scipy reports min(W+, W−) when two-sided)
w_minus = n * (n + 1) / 2 - v
r_rb = (v - w_minus) / (v + w_minus)  # matched-pairs rank-biserial
walsh = np.add.outer(nz, nz)[np.triu_indices(n)] / 2
hl = float(np.median(walsh))  # Hodges–Lehmann pseudo-median of the non-zero differences
median_d = float(np.median(d))

# %% Result
alpha = 0.05
size = magnitude(r_rb, (0.1, 0.3, 0.5))
significance = (
    f"The change is statistically significant ({cs.fmt_p(p)})." if p < alpha
    else f"The data are compatible with no systematic change ({cs.fmt_p(p)})."
)
summary = (
    f"The median difference {a} − {b} was {median_d:.2f} across {len(d)} pairs ({n_zero} ties at zero). "
    f"{significance} The matched-pairs rank-biserial correlation is {size} (r = {r_rb:.2f})."
)
cs.publish({
    "method": "nonparam.wilcoxon_signed_rank",
    "methodVersion": "2.0.1",
    "title": "Wilcoxon signed-rank test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": len(d),
    "summary": summary,
    "apa": f"V = {v:g}, {cs.fmt_p(p)}, r = {cs.fmt_num(r_rb, leading_zero=False)}",
    "statistics": [
        {"key": "v", "label": "V (sum of positive ranks)", "value": v},
        {"key": "p", "label": "p", "value": p, "format": "p"},
        {"key": "hl_estimate", "label": "Pseudo-median difference", "value": hl},
    ],
    "tables": [{
        "key": "descriptives", "title": "Paired differences",
        "columns": [{"key": "pairs", "label": "Pairs", "type": "integer"}, {"key": "zero", "label": "Zero differences", "type": "integer"},
                    {"key": "positive", "label": f"{a} > {b}", "type": "integer"}, {"key": "negative", "label": f"{a} < {b}", "type": "integer"},
                    {"key": "median", "label": "Median difference", "type": "number"}],
        "rows": [{"pairs": len(d), "zero": n_zero, "positive": int((nz > 0).sum()), "negative": int((nz < 0).sum()), "median": median_d}],
    }],
    "effectSizes": [{"key": "rank_biserial", "label": "Matched-pairs rank-biserial r", "value": r_rb, "method": "(W+ − W−) / (W+ + W−)",
                     "magnitude": size, "ruleSet": "Cohen (1988), r"}],
    "assumptions": [{"key": "symmetry", "label": "Symmetric differences", "status": "info",
                     "detail": "The test assumes the differences are symmetric around their median; otherwise read it as a sign-like test."}],
    "warnings": warnings,
    "notes": [f"Differences rounded to 10 decimals, then zero differences dropped; {'exact' if method == 'exact' else 'normal approximation with tie correction'}; alternative: {alternative}."],
    "values": {"v": v, "p": p, "n": n, "n_zero": n_zero, "rank_biserial": r_rb, "hl_estimate": hl, "median_diff": median_d, "method": method},
    "charts": [cs.chart("pairs", "paired-lines", f"{a} and {b} per row", {
        "subject": cs.col("Row", [str(i + 1) for i in range(min(len(d), 2500))] * 2, "categorical"),
        "condition": cs.col("Measurement", [a] * min(len(d), 2500) + [b] * min(len(d), 2500), "categorical", levels=[a, b]),
        "value": cs.col("Value", np.concatenate([df[a].to_numpy(dtype=float)[:2500], df[b].to_numpy(dtype=float)[:2500]]), "numeric")})],
})
R

The exact script CodeSplash ran for example “Sleep ties zero” · R version 4.5.1 (2025-06-13)

# Wilcoxon signed-rank test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.wilcoxon_signed_rank 2.0.1 · spec b8e0aaa0496d3252
# Dataset: sleep_wide (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/sleep_wide.parquet", col_select = c("drug1", "drug2")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("drug1", "drug2")]), , 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("drug1", "drug2"))  # 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
a <- "drug1"
b <- "drug2"
d <- df[[a]] - df[[b]]
d <- round(d * 1e10) / 1e10  # rounded to 10 decimals so floating-point noise is not a difference (same in Python)
n_zero <- sum(d == 0)
nz <- d[d != 0]  # zero differences are dropped (R's default)
n <- length(nz)
if (n == 0) stop("All paired differences are zero.")
alternative <- "two-sided"
correct <- TRUE  # continuity correction (pinned)
method <- "asymptotic"
ties <- length(unique(abs(nz))) < n
if (method == "exact" && (ties || n_zero > 0)) {
  method <- "asymptotic"
  warnings <- c(warnings, "Ties or zero differences: the exact p-value is unavailable, so the tie-corrected normal approximation was used.")
}

res <- wilcox.test(nz, alternative = sub("-", ".", alternative, fixed = TRUE), exact = method == "exact", correct = correct)
p <- res$p.value
v <- unname(res$statistic)  # V = sum of positive ranks
w_minus <- n * (n + 1) / 2 - v
r_rb <- (v - w_minus) / (v + w_minus)  # matched-pairs rank-biserial
walsh <- outer(nz, nz, "+") / 2
hl <- median(walsh[upper.tri(walsh, diag = TRUE)])  # Hodges-Lehmann pseudo-median of the non-zero differences
median_d <- median(d)

# %% Result
alpha <- 0.05
size <- magnitude(r_rb, c(0.1, 0.3, 0.5))
significance <- if (p < alpha) {
  sprintf("The change is statistically significant (%s).", cs_fmt_p(p))
} else {
  sprintf("The data are compatible with no systematic change (%s).", cs_fmt_p(p))
}
summary <- sprintf("The median difference %s − %s was %.2f across %d pairs (%d ties at zero). %s The matched-pairs rank-biserial correlation is %s (r = %.2f).",
                   a, b, median_d, length(d), n_zero, significance, size, r_rb)
nn <- length(d)
cs_publish(list(
  method = "nonparam.wilcoxon_signed_rank",
  methodVersion = "2.0.1",
  title = "Wilcoxon signed-rank test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = length(d),
  summary = summary,
  apa = sprintf("V = %s, %s, r = %s", format(v), cs_fmt_p(p), cs_fmt_num(r_rb, leading_zero = FALSE)),
  statistics = list(
    list(key = "v", label = "V (sum of positive ranks)", value = v),
    list(key = "p", label = "p", value = p, format = "p"),
    list(key = "hl_estimate", label = "Pseudo-median difference", value = hl)
  ),
  tables = list(list(
    key = "descriptives", title = "Paired differences",
    columns = list(list(key = "pairs", label = "Pairs", type = "integer"), list(key = "zero", label = "Zero differences", type = "integer"),
                   list(key = "positive", label = sprintf("%s > %s", a, b), type = "integer"), list(key = "negative", label = sprintf("%s < %s", a, b), type = "integer"),
                   list(key = "median", label = "Median difference", type = "number")),
    rows = data.frame(pairs = length(d), zero = n_zero, positive = sum(nz > 0), negative = sum(nz < 0), median = median_d)
  )),
  effectSizes = list(list(key = "rank_biserial", label = "Matched-pairs rank-biserial r", value = r_rb, method = "(W+ − W−) / (W+ + W−)",
                          magnitude = size, ruleSet = "Cohen (1988), r")),
  assumptions = list(list(key = "symmetry", label = "Symmetric differences", status = "info",
                          detail = "The test assumes the differences are symmetric around their median; otherwise read it as a sign-like test.")),
  warnings = warnings,
  notes = list(sprintf("Differences rounded to 10 decimals, then zero differences dropped; %s; alternative: %s.", if (method == "exact") "exact" else "normal approximation with tie correction", alternative)),
  values = list(v = v, p = p, n = n, n_zero = n_zero, rank_biserial = r_rb, hl_estimate = hl, median_diff = median_d, method = method),
  charts = list(cs_chart("pairs", "paired-lines", sprintf("%s and %s per row", a, b), list(
    subject = cs_col("Row", rep(as.character(seq_len(min(nn, 2500))), 2), "categorical"),
    condition = cs_col("Measurement", rep(c(a, b), each = min(nn, 2500)), "categorical", levels = c(a, b)),
    value = cs_col("Value", c(head(df[[a]], 2500), head(df[[b]], 2500)), "numeric"))))
))

Sources

  • Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics Bulletin, 1, 80–83.

From the CodeSplash method registry · nonparam.wilcoxon_signed_rank v2.0.1.