Skip to content

BCompare groups · nonparam.sign

Sign test (median, one sample or paired)

Is the median (or the median difference of paired values) different from a reference value?

Counts values above and below the reference (zeros dropped) and tests the split with an exact binomial test. Makes no assumption about the shape of the distribution. Reports a distribution-free confidence interval for the median from order statistics.

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

A real result

Example “Paired sleep”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Sign test (paired)Recorded · Python and R agreeRecorded 2026-11-25 · 15 values compared
R

sign test: 0/9 positive, p = .004

Above the reference
0
Below the reference
9
p (exact)
.004
Median drug1 − drug2
−1.300

Plots

Distribution of drug1 − drug2How is one numeric variable distributed?
View data
drug1 − drug2
−1.200
−2.400
−1.300
−1.300
0
−1
−1.800
−0.8000
−4.600
−1.400

Assumptions

  • Values equal to the reference — 1 value(s) equal 0 and were dropped.

Signs and intervals

QuantityEstimateCI lowCI high
Proportion above 0 (Clopper–Pearson)000.3363
Median (order statistics, 97.9% coverage)−1.300−2.400−0.8000
  • H0: median drug1 − drug2 = 0; alternative: two-sided. The median interval is two-sided with the achievable coverage nearest above 95%.
Python

sign test: 0/9 positive, p = .004

Above the reference
0
Below the reference
9
p (exact)
.004
Median drug1 − drug2
−1.300

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

Assumptions

  • Values equal to the reference — 1 value(s) equal 0 and were dropped.

Signs and intervals

QuantityEstimateCI lowCI high
Proportion above 0 (Clopper–Pearson)000.3363
Median (order statistics, 97.9% coverage)−1.300−2.400−0.8000
  • H0: median drug1 − drug2 = 0; alternative: two-sided. The median interval is two-sided with the achievable coverage nearest above 95%.

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

  • Paired sleepsleep_wide · outcome: drug1 · second: drug2
  • One sample greatermtcars · outcome: mpg
  • Missing valuesairquality · outcome: Ozone
  • Float noise pairedsta_float_noise · outcome: after · second: before
  • Median ci boundary n3mtcars · outcome: mpg
  • Median ci boundary n5m1_pvalues · outcome: p
  • Median ci boundary n7aud3_diar_ref · outcome: end · second: start
  • Median ci boundary n7 highaud3_diar_ref · outcome: end · second: start

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
  • Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
  • Non-parametric alternatives · Statistics Guide · Additional considerations

What you need

Variable / first measurementnumeric · 1 column
The variable (one sample) or the first measurement (paired).
Second measurement (paired)numeric · 0–1 column
Optional: the test then uses the differences first − second.

Choices you make

hypothesis

Reference mediandefault 0

Median (or median difference) under H0.

Alternative hypothesisdefault two-sided

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

  • Median ≠ reference(default) — Tests for the median differing from the reference in either direction; keep it unless you fixed a direction before seeing the data.
  • Median > reference — Tests only for a median above the reference; pick it only if you fixed this direction before seeing the data.
  • Median < reference — Tests only for a median below the reference; pick it only if you fixed this direction before seeing the data.
Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

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.

  • Values equal to the reference

    They carry no sign and are dropped.

What it reports

  • Tests: Median differs from the reference
n_pos
How many independent units the analysis used; it sets precision and power.
n_neg
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.
n
How many independent units the analysis used; it sets precision and power.
reference
The value each observation or paired difference is compared with; counts above and below it drive the test.
p
How surprising your data would be if the null hypothesis were true, as a probability.
prop_pos
Tests a median, or paired differences, by counting values above and below it. It ignores how far away they are.
prop_ci_low
A range of effect values compatible with your data at the chosen confidence level.
prop_ci_high
A range of effect values compatible with your data at the chosen confidence level.
median
The middle value when the data are sorted; half the values lie on each side.
median_ci_low
A range of effect values compatible with your data at the chosen confidence level.
median_ci_high
A range of effect values compatible with your data at the chosen confidence level.
median_ci_level
Tests a median, or paired differences, by counting values above and below it. It ignores how far away they are.
design
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

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

  • Differences from the reference value are rounded to 10 decimals (rint(d·10¹⁰)/10¹⁰ in both engines) before signs are counted, so floating-point noise is not counted as above or below.
  • scipy.stats.binomtest and R binom.test use the same two-sided rule (outcomes no more likely than the observed, relative tolerance 1e-7) and Clopper–Pearson intervals.
  • The median interval compares the binomial tail with (1 − conf)/2 within a relative 1e-12 in both engines, so a tail exactly on the boundary counts although R's pbinom(0, 3, 0.5) is 0.12500000000000003.
Python

The exact script CodeSplash ran for example “Paired sleep” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Sign test (median, one sample or paired)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.sign 2.0.2 · spec 489cf8f38c930040
# 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
from codesplash.stats import robust

# %% 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)

# %% Test
y = "drug1"
mu = 0
alternative = "two-sided"
conf = 0.95
y2 = "drug2"
x = df[y].to_numpy(dtype=float) - df[y2].to_numpy(dtype=float)
design, what = "paired", f"{y} − {y2}"
dm = np.rint((x - mu) * 1e10) / 1e10  # differences from the reference, rounded to 10 decimals (floating-point noise is not a sign)
n_pos, n_neg = int((dm > 0).sum()), int((dm < 0).sum())
n_zero = len(x) - n_pos - n_neg
n = n_pos + n_neg
if n == 0:
    raise ValueError("Every value equals the reference, so the sign test has nothing to test")
res = stats.binomtest(n_pos, n, 0.5, alternative=alternative)  # exact binomial (R: binom.test)
p = float(res.pvalue)
pci = res.proportion_ci(confidence_level=conf, method="exact")  # Clopper–Pearson, same sidedness as the test
m_low, m_high, m_level = robust.median_ci(x, conf)  # order-statistic interval for the median
median = float(np.median(x))

# %% Assumptions
assumptions = [{"key": "ties", "label": "Values equal to the reference", "status": "warn" if n_zero > 0.2 * len(x) else ("info" if n_zero else "pass"),
                "detail": f"{n_zero} value(s) equal {mu:g} and were dropped." if n_zero else "No value equals the reference."}]

# %% Result
values = {"n_pos": n_pos, "n_neg": n_neg, "n_zero": n_zero, "n": n, "reference": mu, "p": p, "prop_pos": n_pos / n, "prop_ci_low": float(pci.low),
          "prop_ci_high": float(pci.high), "median": median, "median_ci_low": m_low, "median_ci_high": m_high, "median_ci_level": m_level,
          "design": design}
values["missing_share"] = n_dropped / n_input if n_input else 0.0  # consult-a-statistician input
cs.publish({
    "method": "nonparam.sign",
    "methodVersion": "2.0.2",
    "title": "Sign test" + (" (paired)" if design == "paired" else ""),
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": len(x),
    "summary": f"{n_pos} above and {n_neg} below {mu:g} ({n_zero} ties dropped); median {what} = {median:.3f}; exact {cs.fmt_p(p)}.",
    "apa": f"sign test: {n_pos}/{n} positive, {cs.fmt_p(p)}",
    "statistics": [{"key": "n_pos", "label": "Above the reference", "value": n_pos, "format": "integer"},
                   {"key": "n_neg", "label": "Below the reference", "value": n_neg, "format": "integer"},
                   {"key": "p", "label": "p (exact)", "value": p, "format": "p"},
                   {"key": "median", "label": f"Median {what}", "value": median}],
    "tables": [{"key": "summary", "title": "Signs and intervals", "columns": [
        {"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
        {"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"}],
        "rows": [{"quantity": f"Proportion above {mu:g} (Clopper–Pearson)", "estimate": n_pos / n, "ci_low": float(pci.low), "ci_high": float(pci.high)},
                 {"quantity": f"Median (order statistics, {m_level:.1%} coverage)" if np.isfinite(m_level) else "Median (too few values for an interval)",
                  "estimate": median, "ci_low": m_low, "ci_high": m_high}]}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"H0: median {what} = {mu:g}; alternative: {alternative}. The median interval is two-sided with the achievable coverage nearest above {conf:.0%}."],
    "values": values,
    "charts": [cs.chart("distribution", "histogram", f"Distribution of {what}", {"x": cs.col(what, x[:5000], "numeric")})],
})
R

The exact script CodeSplash ran for example “Paired sleep” · R version 4.5.1 (2025-06-13)

# Sign test (median, one sample or paired)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.sign 2.0.2 · spec 489cf8f38c930040
# 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)

# %% Test
y <- "drug1"
mu <- 0
alternative <- "two-sided"
conf <- 0.95
y2 <- "drug2"
x <- df[[y]] - df[[y2]]
design <- "paired"
what <- sprintf("%s − %s", y, y2)
dm <- round((x - mu) * 1e10) / 1e10  # differences from the reference, rounded to 10 decimals (floating-point noise is not a sign)
n_pos <- sum(dm > 0)
n_neg <- sum(dm < 0)
n_zero <- length(x) - n_pos - n_neg
n <- n_pos + n_neg
if (n == 0) stop("Every value equals the reference, so the sign test has nothing to test")
res <- binom.test(n_pos, n, 0.5, alternative = sub("-", ".", alternative, fixed = TRUE), conf.level = conf)  # exact, Clopper-Pearson
p <- res$p.value
mci <- cs_median_ci(x, conf)  # order-statistic interval for the median
median_x <- median(x)

# %% Assumptions
assumptions <- list(list(key = "ties", label = "Values equal to the reference",
                         status = if (n_zero > 0.2 * length(x)) "warn" else if (n_zero > 0) "info" else "pass",
                         detail = if (n_zero > 0) sprintf("%d value(s) equal %s and were dropped.", n_zero, format(mu)) else "No value equals the reference."))

# %% Result
values <- list(n_pos = n_pos, n_neg = n_neg, n_zero = n_zero, n = n, reference = mu, p = p, prop_pos = n_pos / n, prop_ci_low = res$conf.int[1],
               prop_ci_high = res$conf.int[2], median = median_x, median_ci_low = unname(mci["low"]), median_ci_high = unname(mci["high"]),
               median_ci_level = unname(mci["conf"]), design = design)
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0  # consult-a-statistician input
cs_publish(list(
  method = "nonparam.sign",
  methodVersion = "2.0.2",
  title = paste0("Sign test", if (design == "paired") " (paired)" else ""),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = length(x),
  summary = sprintf("%d above and %d below %s (%d ties dropped); median %s = %.3f; exact %s.", n_pos, n_neg, format(mu), n_zero, what, median_x, cs_fmt_p(p)),
  apa = sprintf("sign test: %d/%d positive, %s", n_pos, n, cs_fmt_p(p)),
  statistics = list(list(key = "n_pos", label = "Above the reference", value = n_pos, format = "integer"),
                    list(key = "n_neg", label = "Below the reference", value = n_neg, format = "integer"),
                    list(key = "p", label = "p (exact)", value = p, format = "p"),
                    list(key = "median", label = paste("Median", what), value = median_x)),
  tables = list(list(key = "summary", title = "Signs and intervals",
                     columns = list(list(key = "quantity", label = "Quantity", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                                    list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number")),
                     rows = list(list(quantity = sprintf("Proportion above %s (Clopper–Pearson)", format(mu)), estimate = n_pos / n,
                                      ci_low = res$conf.int[1], ci_high = res$conf.int[2]),
                                 list(quantity = if (is.finite(mci[["conf"]])) sprintf("Median (order statistics, %.1f%% coverage)", mci[["conf"]] * 100)
                                                 else "Median (too few values for an interval)",
                                      estimate = median_x, ci_low = unname(mci["low"]), ci_high = unname(mci["high"]))))),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("H0: median %s = %s; alternative: %s. The median interval is two-sided with the achievable coverage nearest above %.0f%%.",
                       what, format(mu), alternative, conf * 100)),
  values = values,
  charts = list(cs_chart("distribution", "histogram", sprintf("Distribution of %s", what), list(x = cs_col(what, head(x, 5000), "numeric"))))
))

Sources

  • Conover, W. J. (1999). Practical nonparametric statistics (3rd ed.), §3.4.
  • Hollander, M., Wolfe, D. A., & Chicken, E. (2014). Nonparametric statistical methods (3rd ed.), ch. 3.

From the CodeSplash method registry · nonparam.sign v2.0.2.