EProportions & counts · proportion.mcnemar
McNemar's test (paired proportions)
Did the share of an outcome change between two paired measurements?
Compares two paired yes/no measurements on the same subjects (before/after, two raters, two tests) through the discordant pairs: asymptotic, continuity-corrected, exact binomial and mid-p versions, the paired difference in proportions (Newcombe interval) and the conditional odds ratio.
A real result
Example “Approval auto”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
McNemar's χ² test, p < .001, OR = 1.74, 95% CI [1.33, 2.30]
- p (McNemar's χ² test)
- < .001
- χ² (uncorrected)
- 17.356
- p (asymptotic)
- < .001
- p (continuity-corrected)
- < .001
- p (exact)
- < .001
- p (mid-p)
- < .001
Effect size
- Difference in proportions (paired) 0.0400 95% CI [0.0212, 0.0587]
- Conditional odds ratio (b / c) 1.744 95% CI [1.329, 2.301]
Plots
Wilson intervals (each ignores the pairing; the test uses the discordant pairs).
View data
| Proportion approve | high | measurement | low |
|---|---|---|---|
| 0.5900 | 0.6139 | first | 0.5657 |
| 0.5500 | 0.5742 | second | 0.5255 |
Assumptions
- Enough discordant pairs — 236 discordant pairs (≥ 25).
- Paired observations — Each row holds both measurements of one subject.
Paired table
| first \ second | approve | not approve | Total |
|---|---|---|---|
| approve | 794 | 150 | 944 |
| not approve | 86 | 570 | 656 |
- Event: approve; b = approve in first only, c = approve in second only; difference = first − second.
McNemar's χ² test, p < .001, OR = 1.74, 95% CI [1.33, 2.30]
- p (McNemar's χ² test)
- < .001
- χ² (uncorrected)
- 17.356
- p (asymptotic)
- < .001
- p (continuity-corrected)
- < .001
- p (exact)
- < .001
- p (mid-p)
- < .001
Effect size
- Difference in proportions (paired) 0.0400 95% CI [0.0212, 0.0587]
- Conditional odds ratio (b / c) 1.744 95% CI [1.329, 2.301]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough discordant pairs — 236 discordant pairs (≥ 25).
- Paired observations — Each row holds both measurements of one subject.
Paired table
| first \ second | approve | not approve | Total |
|---|---|---|---|
| approve | 794 | 150 | 944 |
| not approve | 86 | 570 | 656 |
- Event: approve; b = approve in first only, c = approve in second only; difference = first − second.
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
- Approval autoapproval · first: first · second: second
- Small auto exactsymptoms · first: before · second: after
- Corrected 90approval · first: first · second: second
- Midpsymptoms · first: before · second: after
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Study design: independent / paired / repeated / clustered · Statistics Guide · Step 0 — Prepare your data
- Paired proportions: McNemar · Statistics Guide · E — Compare proportions / frequencies
- Compare to gold standard: McNemar (paired) · Statistics Guide · H — Diagnostic accuracy
- Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
What you need
- First measurementcategorical / boolean · 1 column · 2–2 levels
- The first yes/no measurement on each subject (e.g. before).
- Second measurementcategorical / boolean · 1 column · 2–2 levels
- The second measurement on the same subjects, with the same two levels.
Choices you make
hypothesis
- Event leveldefault —
The level counted as the event in both columns (default the last stored level — true for true/false columns).
- Testdefault auto
How the p-value is computed. Automatic uses the exact binomial when there are fewer than 25 discordant pairs.
- Automatic: exact if fewer than 25 discordant pairs(default) — Uses the exact test with under 25 discordant pairs and χ² otherwise; the usual choice.
- Asymptotic χ² (no correction) — Uses χ² with no continuity correction; accurate with many discordant pairs.
- χ² with continuity correction (Edwards) — Uses χ² with Edwards's continuity correction; more conservative, and matches some older software.
- Exact binomial — Uses the binomial test on discordant pairs; valid at any size, but conservative in small samples.
- Mid-p exact — An exact test less half the observed outcome's probability; less conservative, and sound in small samples.
- 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.
Enough discordant pairs
The χ² versions need at least 25 discordant pairs (b + c); below that use the exact or mid-p test.
- If violated → Exact McNemar test — The exact binomial test on the discordant pairs is valid however few there are.
Paired observations
Both columns describe the same subject on each row.
What it reports
- Tests: Change between the paired measurements
- n
- How many independent units the analysis used; it sets precision and power.
- a
- Asks whether rows within groups are closer than random sets of the same sizes; A = 1 − δ/E(δ).
- b
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- c
- Paired subjects whose two outcomes differ. McNemar's test uses these pairs and ignores the rest.
- d
- A difference in means expressed in standard deviations.
- discordant
- Paired subjects whose two outcomes differ. McNemar's test uses these pairs and ignores the rest.
- p_first
- A value between 0 and 1 — a share, a rate or a probability.
- p_second
- A value between 0 and 1 — a share, a rate or a probability.
- diff
- Paired subjects whose two outcomes differ. McNemar's test uses these pairs and ignores the rest.
- diff_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- diff_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- chi2_cc
- A sum of squared, scaled differences between observed and expected counts or estimates.
- p_asymptotic
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_corrected
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_exact
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_midp
- How surprising your data would be if the null hypothesis were true, as a probability.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- odds_ratio
- How many times higher the odds of an event are in one group than another; 1 means no difference.
- or_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- or_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- event
- In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
- method_label
- 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
- The exact odds-ratio interval inverts Clopper–Pearson limits from Boost's beta quantile (scipy) and R's qbeta (agreement ≈ 1e-12).
The exact script CodeSplash ran for example “Approval auto” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# McNemar's test (paired proportions)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.mcnemar 1.0.1 · spec 177069cca281154b
# Dataset: approval (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import proportions as csp # McNemar variants, Newcombe paired interval (twins of codesplashr)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/approval.parquet", columns=["first", "second"])
n_input = len(df)
df["first"] = pd.Categorical(df["first"], categories=["disapprove", "approve"]) # stored level order
df["second"] = pd.Categorical(df["second"], categories=["disapprove", "approve"]) # stored level order
df = df.dropna(subset=["first", "second"]) # listwise deletion over the analysis columns
df["first"] = df["first"].cat.remove_unused_categories()
df["second"] = df["second"].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, ["first", "second"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
f1, f2 = "first", "second"
levels1 = ["disapprove", "approve"] # stored level order
event = "approve" # default: the last level ("true")
if event not in levels1:
raise ValueError(f"{event!r} is not a level of {f1}")
if event not in set(df[f2].astype(str)) | set(map(str, df[f2].cat.categories)):
raise ValueError(f"{f2} has no level {event!r}: both columns need the same levels")
e1 = (df[f1].astype(str) == event).to_numpy()
e2 = (df[f2].astype(str) == event).to_numpy()
a, b = int(np.sum(e1 & e2)), int(np.sum(e1 & ~e2)) # b: event in the first measurement only
c, d = int(np.sum(~e1 & e2)), int(np.sum(~e1 & ~e2)) # c: event in the second measurement only
n = a + b + c + d
conf = 0.95
method = "auto"
if method == "auto":
method = "exact" if b + c < 25 else "asymptotic"
labels = {"asymptotic": "McNemar's χ² test", "corrected": "McNemar's χ² test with continuity correction",
"exact": "exact McNemar test", "midp": "mid-p McNemar test"}
mc = csp.mcnemar(b, c) # asymptotic, corrected (Edwards), exact binomial, mid-p
p = mc[{"asymptotic": "p_asymptotic", "corrected": "p_corrected", "exact": "p_exact", "midp": "p_midp"}[method]]
p1, p2 = (a + b) / n, (a + c) / n
diff = p1 - p2 # = (b − c) / n
diff_low, diff_high = csp.newcombe_paired_ci(a, b, c, d, conf) # Newcombe (1998) method 10
odds = b / c if c > 0 else (math.inf if b > 0 else math.nan) # conditional (matched-pairs) odds ratio
if b + c > 0:
lo, hi = csp.prop_ci(b, b + c, conf, "clopper-pearson") # exact interval for b / (b + c), mapped to b / c
or_low = lo / (1 - lo)
or_high = hi / (1 - hi) if hi < 1 else math.inf
else:
or_low = or_high = math.nan
# %% Assumptions
m = b + c
if method in ("asymptotic", "corrected") and m < 25:
status, detail = "warn", f"Only {m} discordant pairs (< 25): the χ² approximation is poor; use the exact or mid-p test."
elif method in ("asymptotic", "corrected"):
status, detail = "pass", f"{m} discordant pairs (≥ 25)."
else:
status, detail = "info", f"{m} discordant pairs; the {labels[method]} needs no large-sample approximation."
assumptions = [
{"key": "discordant", "label": "Enough discordant pairs", "status": status, "detail": detail},
{"key": "pairing", "label": "Paired observations", "status": "info", "detail": "Each row holds both measurements of one subject."},
]
# %% Result
alpha = 1 - conf
summary = (
f"{f1} = {event} in {p1:.1%} and {f2} = {event} in {p2:.1%} of {n} subjects (difference {diff:.3f}, "
f"{conf:.0%} CI [{diff_low:.3f}, {diff_high:.3f}]); {labels[method]} {cs.fmt_p(p)}."
)
w1, w2 = csp.prop_ci(a + b, n, conf, "wilson"), csp.prop_ci(a + c, n, conf, "wilson")
cs.publish({
"method": "proportion.mcnemar",
"methodVersion": "1.0.1",
"title": "McNemar's test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{labels[method]}, {cs.fmt_p(p)}, OR = {cs.fmt_num(odds)}, {conf:.0%} CI [{cs.fmt_num(or_low)}, {cs.fmt_num(or_high)}]",
"statistics": [
{"key": "p", "label": f"p ({labels[method]})", "value": p, "format": "p"},
{"key": "chi2", "label": "χ² (uncorrected)", "value": mc["chi2"]},
{"key": "p_asymptotic", "label": "p (asymptotic)", "value": mc["p_asymptotic"], "format": "p"},
{"key": "p_corrected", "label": "p (continuity-corrected)", "value": mc["p_corrected"], "format": "p"},
{"key": "p_exact", "label": "p (exact)", "value": mc["p_exact"], "format": "p"},
{"key": "p_midp", "label": "p (mid-p)", "value": mc["p_midp"], "format": "p"},
],
"tables": [{
"key": "pairs", "title": "Paired table",
"columns": [{"key": "row", "label": f"{f1} \\ {f2}", "type": "string"}, {"key": "event", "label": event, "type": "integer"},
{"key": "other", "label": f"not {event}", "type": "integer"}, {"key": "total", "label": "Total", "type": "integer"}],
"rows": [{"row": event, "event": a, "other": b, "total": a + b}, {"row": f"not {event}", "event": c, "other": d, "total": c + d}],
}],
"effectSizes": [
{"key": "diff", "label": "Difference in proportions (paired)", "value": diff, "ciLow": diff_low, "ciHigh": diff_high, "ciLevel": conf,
"method": "Newcombe (1998) method 10"},
{"key": "odds_ratio", "label": "Conditional odds ratio (b / c)", "value": odds, "ciLow": or_low, "ciHigh": or_high, "ciLevel": conf,
"method": "exact (Clopper–Pearson on b / (b + c))"},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event}; b = {event} in {f1} only, c = {event} in {f2} only; difference = {f1} − {f2}."],
"charts": [cs.chart(
"proportions", "forest", f"Proportion {event}",
{"label": cs.col("measurement", [f1, f2]), "estimate": cs.col(f"Proportion {event}", [p1, p2]),
"low": cs.col("low", [w1[0], w2[0]]), "high": cs.col("high", [w1[1], w2[1]])},
note="Wilson intervals (each ignores the pairing; the test uses the discordant pairs).",
)],
"values": {
"n": n, "a": a, "b": b, "c": c, "d": d, "discordant": b + c, "p_first": p1, "p_second": p2,
"diff": diff, "diff_ci_low": diff_low, "diff_ci_high": diff_high,
"chi2": mc["chi2"], "chi2_cc": mc["chi2_cc"], "p_asymptotic": mc["p_asymptotic"], "p_corrected": mc["p_corrected"],
"p_exact": mc["p_exact"], "p_midp": mc["p_midp"], "p": p,
"odds_ratio": odds, "or_ci_low": or_low, "or_ci_high": or_high, "event": event, "method_label": labels[method],
},
})
The exact script CodeSplash ran for example “Approval auto” · R version 4.5.1 (2025-06-13)
# McNemar's test (paired proportions)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.mcnemar 1.0.1 · spec 177069cca281154b
# Dataset: approval (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_mcnemar, cs_newcombe_paired_ci, cs_prop_ci (twins of codesplash.stats)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/approval.parquet", col_select = c("first", "second")))
n_input <- nrow(df)
df[["first"]] <- factor(df[["first"]], levels = c("disapprove", "approve")) # stored level order
df[["second"]] <- factor(df[["second"]], levels = c("disapprove", "approve")) # stored level order
df <- df[stats::complete.cases(df[c("first", "second")]), , 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("first", "second")) # infinite values stop the run (registry/errors.yaml)
# %% Test
f1 <- "first"
f2 <- "second"
levels1 <- c("disapprove", "approve") # stored level order
event <- "approve" # default: the last level ("true")
if (!event %in% levels1) stop(sprintf("'%s' is not a level of %s", event, f1))
if (!event %in% union(as.character(df[[f2]]), levels(df[[f2]]))) stop(sprintf("%s has no level '%s': both columns need the same levels", f2, event))
e1 <- as.character(df[[f1]]) == event
e2 <- as.character(df[[f2]]) == event
a <- sum(e1 & e2)
b <- sum(e1 & !e2) # event in the first measurement only
c <- sum(!e1 & e2) # event in the second measurement only
d <- sum(!e1 & !e2)
n <- a + b + c + d
conf <- 0.95
method <- "auto"
if (method == "auto") method <- if (b + c < 25) "exact" else "asymptotic"
labels <- c(asymptotic = "McNemar's χ² test", corrected = "McNemar's χ² test with continuity correction",
exact = "exact McNemar test", midp = "mid-p McNemar test")
mc <- cs_mcnemar(b, c) # asymptotic (= mcnemar.test(correct = FALSE)), corrected, exact binomial, mid-p
p <- mc[[c(asymptotic = "p_asymptotic", corrected = "p_corrected", exact = "p_exact", midp = "p_midp")[[method]]]]
p1 <- (a + b) / n
p2 <- (a + c) / n
diff <- p1 - p2 # = (b - c) / n
diff_ci <- cs_newcombe_paired_ci(a, b, c, d, conf) # Newcombe (1998) method 10
odds <- if (c > 0) b / c else if (b > 0) Inf else NaN # conditional (matched-pairs) odds ratio
if (b + c > 0) {
ci <- cs_prop_ci(b, b + c, conf, "clopper-pearson") # exact interval for b / (b + c), mapped to b / c
or_low <- ci[1] / (1 - ci[1])
or_high <- if (ci[2] < 1) ci[2] / (1 - ci[2]) else Inf
} else {
or_low <- NaN
or_high <- NaN
}
# %% Assumptions
m <- b + c
if (method %in% c("asymptotic", "corrected") && m < 25) {
status <- "warn"
detail <- sprintf("Only %d discordant pairs (< 25): the χ² approximation is poor; use the exact or mid-p test.", m)
} else if (method %in% c("asymptotic", "corrected")) {
status <- "pass"
detail <- sprintf("%d discordant pairs (≥ 25).", m)
} else {
status <- "info"
detail <- sprintf("%d discordant pairs; the %s needs no large-sample approximation.", m, labels[[method]])
}
assumptions <- list(
list(key = "discordant", label = "Enough discordant pairs", status = status, detail = detail),
list(key = "pairing", label = "Paired observations", status = "info", detail = "Each row holds both measurements of one subject.")
)
# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("%s = %s in %.1f%% and %s = %s in %.1f%% of %d subjects (difference %.3f, %s CI [%.3f, %.3f]); %s %s.",
f1, event, 100 * p1, f2, event, 100 * p2, n, diff, pct, diff_ci[1], diff_ci[2], labels[[method]], cs_fmt_p(p))
w1 <- cs_prop_ci(a + b, n, conf, "wilson")
w2 <- cs_prop_ci(a + c, n, conf, "wilson")
cs_publish(list(
method = "proportion.mcnemar",
methodVersion = "1.0.1",
title = "McNemar's test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s, %s, OR = %s, %s CI [%s, %s]", labels[[method]], cs_fmt_p(p), cs_fmt_num(odds), pct, cs_fmt_num(or_low), cs_fmt_num(or_high)),
statistics = list(
list(key = "p", label = sprintf("p (%s)", labels[[method]]), value = p, format = "p"),
list(key = "chi2", label = "χ² (uncorrected)", value = mc$chi2),
list(key = "p_asymptotic", label = "p (asymptotic)", value = mc$p_asymptotic, format = "p"),
list(key = "p_corrected", label = "p (continuity-corrected)", value = mc$p_corrected, format = "p"),
list(key = "p_exact", label = "p (exact)", value = mc$p_exact, format = "p"),
list(key = "p_midp", label = "p (mid-p)", value = mc$p_midp, format = "p")
),
tables = list(list(
key = "pairs", title = "Paired table",
columns = list(
list(key = "row", label = paste(f1, "\\", f2), type = "string"), list(key = "event", label = event, type = "integer"),
list(key = "other", label = paste("not", event), type = "integer"), list(key = "total", label = "Total", type = "integer")
),
rows = list(list(row = event, event = a, other = b, total = a + b), list(row = paste("not", event), event = c, other = d, total = c + d))
)),
effectSizes = list(
list(key = "diff", label = "Difference in proportions (paired)", value = diff, ciLow = diff_ci[1], ciHigh = diff_ci[2], ciLevel = conf,
method = "Newcombe (1998) method 10"),
list(key = "odds_ratio", label = "Conditional odds ratio (b / c)", value = odds, ciLow = or_low, ciHigh = or_high, ciLevel = conf,
method = "exact (Clopper–Pearson on b / (b + c))")
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s; b = %s in %s only, c = %s in %s only; difference = %s − %s.", event, event, f1, event, f2, f1, f2)),
charts = list(cs_chart(
"proportions", "forest", paste("Proportion", event),
list(label = cs_col("measurement", c(f1, f2)), estimate = cs_col(paste("Proportion", event), c(p1, p2)),
low = cs_col("low", c(w1[1], w2[1])), high = cs_col("high", c(w1[2], w2[2]))),
note = "Wilson intervals (each ignores the pairing; the test uses the discordant pairs)."
)),
values = list(
n = n, a = a, b = b, c = c, d = d, discordant = b + c, p_first = p1, p_second = p2,
diff = diff, diff_ci_low = diff_ci[1], diff_ci_high = diff_ci[2],
chi2 = mc$chi2, chi2_cc = mc$chi2_cc, p_asymptotic = mc$p_asymptotic, p_corrected = mc$p_corrected,
p_exact = mc$p_exact, p_midp = mc$p_midp, p = p,
odds_ratio = odds, or_ci_low = or_low, or_ci_high = or_high, event = event, method_label = labels[[method]]
)
))
Sources
- McNemar, Q. (1947). Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika, 12, 153–157.
- Edwards, A. L. (1948). Note on the 'correction for continuity' in testing the significance of the difference between correlated proportions. Psychometrika, 13, 185–187.
- Newcombe, R. G. (1998). Improved confidence intervals for the difference between binomial proportions based on paired data. Statistics in Medicine, 17, 2635–2650.
- Fagerland, M. W., Lydersen, S., & Laake, P. (2013). The McNemar test for binary matched-pairs data: mid-p and asymptotic are better than exact conditional. BMC Medical Research Methodology, 13, 91.
From the CodeSplash method registry · proportion.mcnemar v1.0.1.