Pairs without normality: sign and signed-rank tests
Two tests for paired differences, one using only the direction of each change and one using the ranks of its size too.
What runs in CodeSplash
- STAT032Sign test Runs in CodeSplash
- STAT033Wilcoxon signed rank test Runs in CodeSplash
- Sign test (median, one sample or paired) Verified in Python and R
- Wilcoxon signed-rank test Verified in Python and R
You will be able to
- Compute a sign test from counts of positive and negative differences
- Explain what the signed-rank test adds, and the symmetry it assumes
- Choose between paired t, signed-rank and sign tests
Read first
Only the direction
ReadThe sign testSign testTests a median, or paired differences, by counting values above and below it. It ignores how far away they are. throws away everything about each difference except its sign. If the two conditions were interchangeable, a difference would be equally likely to go either way, so the count of positive differences follows a binomial distribution with chance ½.
Differences of exactly zero say nothing about direction, so they drop out.
Work it out
PredictPredict first
In the sleep study, one patient of ten had no difference between drugs. All 9 of the others slept more on drug 2.
How surprising is nine out of nine if the drugs were interchangeable? Count both directions.
Reveal
Below 1 in 100. The chance of all nine in one direction is , and doubling for two directions gives p = .004.
Sizes matter too
ReadThe Wilcoxon signed-rank testWilcoxon signed-rank testRanks the sizes of paired differences, then compares the positive ranks with the negative ones. also uses how big each change is. Rank the absolute differences, then add up the ranks of the positive ones:
Under the null, large and small changes are equally likely to be positive or negative. That needs the differences to be symmetric around their center, so the test is about their pseudo-median, not their median.
Read both results
ReadV = 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
View data
| Measurement | Row | Value |
|---|---|---|
| drug1 | 1 | 0.7000 |
| drug1 | 2 | −1.600 |
| drug1 | 3 | −0.2000 |
| drug1 | 4 | −1.200 |
| drug1 | 5 | −0.1000 |
| drug1 | 6 | 3.400 |
| drug1 | 7 | 3.700 |
| drug1 | 8 | 0.8000 |
| drug1 | 9 | 0 |
| drug1 | 10 | 2 |
| drug2 | 1 | 1.900 |
| drug2 | 2 | 0.8000 |
| drug2 | 3 | 1.100 |
| drug2 | 4 | 0.1000 |
| drug2 | 5 | −0.1000 |
| drug2 | 6 | 4.400 |
| drug2 | 7 | 5.500 |
| drug2 | 8 | 1.600 |
| drug2 | 9 | 4.600 |
| drug2 | 10 | 3.400 |
Assumptions
- Symmetric differences — The test assumes the differences are symmetric around their median; otherwise read it as a sign-like test.
Paired differences
| Pairs | Zero differences | drug1 > drug2 | drug1 < drug2 | Median difference |
|---|---|---|---|---|
| 10 | 1 | 0 | 9 | −1.300 |
- Differences rounded to 10 decimals, then zero differences dropped; normal approximation with tie correction; alternative: two-sided.
The exact R script · R 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"))))
))
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
| Pairs | Zero differences | drug1 > drug2 | drug1 < drug2 | Median difference |
|---|---|---|---|---|
| 10 | 1 | 0 | 9 | −1.300 |
- Differences rounded to 10 decimals, then zero differences dropped; normal approximation with tie correction; alternative: two-sided.
The exact Python script · Python 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")})],
})
No positive differences means V = 0 and p = .009, using the normal approximation because of tied differences. Its Hodges–Lehmann estimate is −1.40 hours.
The sign test gave p = .004 on the same data, and the paired t test p = .003. All three point the same way.
Both rank tests round each difference to 10 decimals first. Subtraction in floating point can leave two equal differences a hair apart, which would break a tie differently in Python and R; rounding keeps the ties, and the two engines, in step.
Choose your test
ReflectThree tests, three levels of what you're willing to believe about the differences:
| Differences are | Use | Tests the |
|---|---|---|
| Roughly normal | Paired t | Mean difference |
| Symmetric, maybe heavy-tailed | Signed-rank | Pseudo-median |
| Skewed, or only direction is trustworthy | Sign | Median |
Think of a recent before-and-after comparison you ran. Which row were your differences in, and did you check?
Check your understanding
CheckpointCheck yourself
Of 10 paired differences, 8 are positive and 2 are negative, none zero. Using the exact two-sided sign test, what is p? Three decimals.
Show the answer
Answer: 0.109
P(X ≥ 8) with X ~ Binomial(10, ½) is 56/1024 ≈ 0.0547; doubling gives about 0.109.
Check yourself
The differences are strongly right-skewed. What should you do about the signed-rank test?
Show the answer
Answer: b
The signed-rank null assumes symmetry. With skewed differences, the sign test has a clean interpretation about the median, at the cost of power.
Check yourself
What happens to paired differences of exactly zero in a sign test?
Show the answer
Answer: b
A zero tells you nothing about direction. CodeSplash reports how many were dropped so you can see it happened.
Check yourself
Paired differences are +1, −2, +3 and +4. Rank them by size, ignoring sign. What is the sum of the ranks of the positive differences?
Show the answer
Answer: 8
Their sizes rank 1, 2, 3 and 4. The positive ones have ranks 1, 3 and 4, which sum to 8.
Check yourself
What does the signed-rank test use that the sign test ignores?
Show the answer
Answer: a
The sign test counts only pluses and minuses. The signed-rank test also ranks how large each difference is, which is why it needs roughly symmetric differences.
Check yourself
Tasters say only whether each new recipe is better or worse than the old one. Which test fits?
Show the answer
Answer: a
With no size to rank or average, the direction of each pair is all you have.
Do it in CodeSplash
In the appThe sign test takes a Variable / first measurement and either a Reference median or a Second measurement. The signed-rank test takes First and Second measurement. Both can run on a single column against a target too.
import pandas as pd
from scipy import stats
df = pd.read_csv("sleep_wide.csv")
d = (df["drug1"] - df["drug2"]).round(10) # as CodeSplash does: no float-noise ties
# Sign test: count the signs and drop zeros.
d = d[d != 0]
print(stats.binomtest(int((d > 0).sum()), len(d), 0.5))
# Signed-rank test with a normal approximation.
print(stats.wilcoxon(d, method="asymptotic", correction=True))df <- read.csv("sleep_wide.csv")
d <- round(df$drug1 - df$drug2, 10) # as CodeSplash does: no float-noise ties
# Sign test: count the signs and drop zeros.
d <- d[d != 0]
binom.test(sum(d > 0), length(d), 0.5)
# Signed-rank test with a normal approximation.
wilcox.test(d, mu = 0, exact = FALSE, correct = TRUE)Recap
Recap- The sign test uses direction only and targets the median of the differences.
- The signed-rank test also uses size, and assumes symmetric differences.
- Zero differences drop out of both.
Concepts in this lesson