Algorithmcore
McNemar's test
Also called McNemar test for paired proportions.
Tests a change in a paired binary outcome using only the discordant pairs, whose split is binomial with p = 1/2 under the null.
- Time
- Θ(m) worstΘ(1) best
- Space
- Θ(1) extra
- Where
- m = the number of discordant pairs b + c
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Quinn McNemar, Allen L. Edwards, 1947
McNemar's test checks whether a binary outcome changes between two paired measurements, such as the same people before and after a treatment, or the two members of matched pairs. Only the discordant pairs, those that changed, carry information about the change. If there is no change in the margins, a discordant pair is equally likely to go either way, so given the number of discordant pairs, the count is . The exact test is a binomial test on that count, and the classical statistic is its large-sample chi-square form.
In plain words
Ask 100 people a yes-or-no question twice, before and after a debate. Most give the same answer both times, and they tell you nothing about a shift. Look only at the people who changed their answer. If the debate had no effect, a changer is as likely to switch from yes to no as from no to yes, like a fair coin. So the question becomes: is the split among the changers too lopsided for a fair coin? With 15 changes one way and 5 the other, the chance of a split at least that uneven is about 4%.
The problem
Model. independent pairs with a binary outcome on each member. The paired table is
| second: yes | second: no | |
|---|---|---|
| first: yes | ||
| first: no |
with cell probabilities . The first margin has and the second .
Hypotheses. : marginal homogeneity, , which is . : . The code is two-sided.
Statistic. The discordant counts and , with ; and .
Null distribution. Exact and conditional: given , , whatever the concordant cells are. Asymptotic: tends to the chi-square law with 1 degree of freedom as the number of pairs grows with fixed.
Rejection rule and size. Reject when . The exact test has size at most for every (proved). The asymptotic test can exceed for small ; the corrected test stayed below for every in an exact computation (measured, not proved).
P-values. Exact: for ; since the law is symmetric, doubling the smaller tail and the minimum-likelihood rule agree. Asymptotic: . Corrected (Edwards): , with floored at 0.
Sensitivity and power. The power depends on the discordant probabilities, not on the margins alone: given , . Many concordant pairs mean few informative pairs. For , and , the exact two-sided test at has power (computed by summing over all tables).
The algorithm
MCNEMAR(b, c, method)- 1
m ← b + c; if m = 0 then return 1 - 2
if method = exact then - 3
s ← C(m, 0) + C(m, 1) + ... + C(m, min(b, c)) ▷ exact integers, C(m, k+1) = C(m, k)(m - k)/(k + 1) - 4
return min(1, 2 s / 2^m) - 5
X2 ← (b - c)^2 / m, or max(0, |b - c| - 1)^2 / m if method = corrected - 6
return P(χ²₁ > X2) ▷ upper tail of chi-square with 1 degree of freedom
The concordant counts and are not inputs. Line L3 is exact, so the p-value is a Fraction before the final conversion. Line L6 uses chi2_sf from the shared helper module, the regularized upper incomplete gamma function ; with 1 degree of freedom it equals .
Example
Opinion before and after a debate. Of 100 people, said yes both times, said no both times, changed from yes to no and from no to yes. Support fell from 55% to 45%.
- Asymptotic: , .
- Corrected: , .
- Exact: , , so .
All three reject at , the exact one only just. Treating the two answers as independent samples instead, a two-sample chi-square test on against gives and : ignoring the pairing throws away the fact that 80 people did not change.
Small counts. With , : asymptotic , corrected , exact . With , : asymptotic , corrected , exact . The asymptotic test is the most liberal. With , it gives and , so it rejects, while the exact p-value is .
The tests check every number above, the fractions exactly.
Correctness
The full proof is in proofs/correctness.md. The pairs are independent, so given which pairs are discordant, each one is (yes, no) with probability independently, and under . The exact p-value is the tail , which by symmetry is twice the lower tail at , and the tail lemma of the binomial test gives size at most given , hence overall. Algebra gives with , the standardized binomial count, so the central limit theorem gives the chi-square limit as .
Proof: Given the discordant total the count b is Binomial(m, 1/2), so the exact p-value is valid and the statistic tends to chi-square with 1 degree of freedomfull
Model. independent pairs, each with a binary outcome before and after (or for the two members of a matched pair). Each pair falls in one of four cells with probabilities (yes, yes), (yes, no), (no, yes) and (no, no). The counts are multinomial. The null hypothesis of marginal homogeneity is , that is , which is . Write .
Claim 1 (the conditional null law). If , then given , with , whatever , , and are. Under , .
Proof. Classify each pair as concordant, (yes, no) or (no, yes). The pairs are independent, so the number of discordant pairs is binomial, and given which pairs are discordant, each of them is (yes, no) with probability , independently of the others. So given , is a sum of independent Bernoulli() variables. The concordant pairs do not enter.
Claim 2 (lines L1 to L4 return the exact two-sided p-value). Let and . The exact p-value is , and
Proof. Let . Then if and only if or . If then , the two sets are disjoint, and by the symmetry they have the same probability, so , which is at most 1 since the two disjoint events have total probability at most 1. If then , every qualifies, and ; the formula gives , which the minimum cuts to 1. Line L3 sums the integers exactly (see Cost for how it finds them), and line L4 forms the fraction exactly. When there is no information and the code returns 1.
Claim 3 (validity). Under , for every , both given and without conditioning.
Proof. Given , is a tail of a finite law, so the lemma on the binomial test correctness page gives . Averaging over gives the unconditional bound.
Claim 4 (the asymptotic statistic). with , the standardized count of a Binomial(, 1/2) variable. Under with fixed, converges in distribution to the chi-square law with 1 degree of freedom as , and the size of the asymptotic test tends to .
Proof. and , so and . Given , is a standardized sum of iid Bernoulli(1/2) variables, so by the central limit theorem, as (Pólya's theorem turns pointwise convergence to a continuous limit into uniform convergence). Since , in probability as . So by bounded convergence, and tends to the square of a standard normal, which is chi-square with 1 degree of freedom. The law is continuous, so the size at the quantile tends to .
The convergence is not uniform in the parameters: for small , stays small and the conditional size of the asymptotic test can be far from . The page and the tests compute it exactly for each . Edwards's corrected statistic has the same limit, because in probability (as stays bounded in probability). That the corrected test keeps its size below is measured, not proved: the tests check it for .
Lines L5 and L6. Line L5 computes or the corrected statistic, and line L6 returns from the regularized incomplete gamma function of the helper module. With 1 degree of freedom this equals , which the tests use as an independent check.
Cost. The exact method sums binomial coefficients. Line L3 finds each from the one before by , an exact integer division because . So the sum takes operations on integers of at most bits, and bit operations. The asymptotic methods take operations plus one incomplete gamma evaluation.
Complexity
The exact method sums binomial coefficients, each from the previous one with one multiplication and one exact division, so it takes arithmetic operations, at most , on integers of at most bits. The asymptotic and corrected methods take operations plus one incomplete gamma evaluation. Only a running sum and one term are stored. For very large the exact tail can instead be found from the regularized incomplete beta function in floating point, as on the binomial test page.
Properties
- Exact test: conservative. Given , the exact size at is at most 0.05 and jumps with : for example 0.0414 at and 0.0129 at .
- Asymptotic test: can be liberal. Given , its exact size exceeded 0.05 for 144 of the values , with the worst case at . Averaged over , for pairs with , the sizes are (exact), (asymptotic) and (corrected); for and , the asymptotic size is , above . These are exact sums over all tables; a simulation with 10000 repetitions (seed 1) agrees for within sampling error.
- Corrected test: close to exact. Edwards's correction gives sizes close to the exact test's, sometimes smaller: at the corrected size is while the exact size is .
- Power. For the alternative in the problem section, the powers at are (exact), (corrected) and (asymptotic, which does not hold its size).
- Uses only discordant pairs. Adding concordant pairs does not change the test. This is right for testing the margins, but the size of the change in proportions, , does depend on .
- Same as a score test. is the score statistic for in the multinomial model, and also the square of the sign test statistic on the pair differences.
Variants and improvements
- Mid-p value. Replace by before doubling. It is less conservative but can exceed .
- Confidence interval. For the difference of the paired proportions , the estimate is with variance estimate ; a Wald interval follows, and score-type intervals behave better for small counts. For , the Clopper-Pearson interval on out of inverts the exact test, by test-interval duality.
- More categories. For a paired table, Bowker's test of symmetry (1948) and the Stuart-Maxwell test of marginal homogeneity extend McNemar's test. For a binary outcome under conditions, Cochran's Q test (1950) does.
- Stratified pairs. With strata, the conditional logistic model for matched pairs generalizes the test, and the Mantel-Haenszel form combines the strata.
When to use it
Use it for a binary outcome measured twice on the same units, or on matched pairs, when the question is whether the proportion of "yes" changed. Use the exact form when is small, say below 25 to 30, or always, since it is cheap. For independent samples use Fisher's exact test or the chi-squared test instead.
Pitfalls
- Testing association instead of change. A chi-squared test of independence on the paired table asks whether the first and second answers are related, which they nearly always are. It does not test a change in the margins.
- Ignoring the pairing. Treating the two measurements as independent samples gets the variance wrong; in the example the p-value rose from 0.025 to 0.157.
- The asymptotic test with few discordant pairs. With its size can be far above , as at . R's
mcnemar.testapplies the continuity correction by default. - Reading "no significant change" as "no change". A large concordant group with few discordant pairs gives little power, however large is.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mcnemar-test/. The authors are listed in prov/H919BT.jsonl.
from fractions import Fraction
from stdist import chi2_sf
def mcnemar_statistic(b: int, c: int, corrected: bool = False) -> float:
"""McNemar's statistic (b - c)^2 / (b + c), or Edwards's corrected
(|b - c| - 1)^2 / (b + c) with the difference floored at 0.
b and c are the two discordant counts of a paired 2 x 2 table: pairs
with (yes, no) and pairs with (no, yes). Returns 0 when b + c = 0.
"""
m = b + c
if m == 0:
return 0.0
diff = abs(b - c)
if corrected:
diff = max(0, diff - 1)
return diff * diff / m
def mcnemar_test(b: int, c: int, method: str = "exact", exact: bool = False) -> float | Fraction:
"""Two-sided p-value of McNemar's test of marginal homogeneity.
method "exact": given m = b + c discordant pairs, b ~ Binomial(m, 1/2)
under the null, and the p-value is twice the smaller binomial tail, from
exact integer sums (with exact=True it is returned as a Fraction).
method "asymptotic": the chi-square tail with 1 degree of freedom of
(b - c)^2 / (b + c). method "corrected": the same with Edwards's
continuity correction. The concordant counts do not enter the test.
"""
if not (isinstance(b, int) and isinstance(c, int)) or b < 0 or c < 0:
raise ValueError("b and c must be non-negative integers")
if method not in ("exact", "asymptotic", "corrected"):
raise ValueError("unknown method")
m = b + c # @line L1
if m == 0:
return Fraction(1) if exact else 1.0
if method == "exact": # @line L2
s, term = 0, 1 # term = C(m, k), updated by C(m, k + 1) = C(m, k) (m - k) / (k + 1)
for k in range(min(b, c) + 1): # @line L3
s += term
term = term * (m - k) // (k + 1)
p = min(Fraction(1), Fraction(2 * s, 2**m)) # @line L4
return p if exact else float(p)
x2 = mcnemar_statistic(b, c, corrected=(method == "corrected")) # @line L5
return chi2_sf(x2, 1) # @line L6
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
mcnemar_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mcnemar-test/. The authors are listed in prov/H919BT.jsonl.
"""Entry point named after the slug. The code lives in mcnemar.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from mcnemar import mcnemar_statistic, mcnemar_test
__all__ = ["mcnemar_statistic", "mcnemar_test"]
test_mcnemar_test.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mcnemar-test/. The authors are listed in prov/H919BT.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from mcnemar_test import mcnemar_statistic, mcnemar_test
METHODS = ("exact", "asymptotic", "corrected")
def test_page_examples() -> None:
assert mcnemar_statistic(15, 5) == 5.0
assert mcnemar_statistic(15, 5, corrected=True) == pytest.approx(4.05)
assert mcnemar_test(15, 5, "asymptotic") == pytest.approx(0.025347, abs=1e-6)
assert mcnemar_test(15, 5, "corrected") == pytest.approx(0.044171, abs=1e-6)
assert mcnemar_test(15, 5, exact=True) == Fraction(5425, 131072)
assert mcnemar_test(9, 2, "asymptotic") == pytest.approx(0.034808, abs=1e-6)
assert mcnemar_test(9, 2, "corrected") == pytest.approx(0.070440, abs=1e-6)
assert mcnemar_test(9, 2, exact=True) == Fraction(67, 1024)
assert mcnemar_test(6, 1, exact=True) == Fraction(1, 8)
assert mcnemar_test(6, 1, "asymptotic") == pytest.approx(0.058782, abs=1e-6)
def test_exact_against_enumeration_of_signs() -> None:
# Under the null, each discordant pair is (yes, no) or (no, yes) with
# probability 1/2. Enumerate all 2^m outcomes and count the ones whose
# imbalance |b - c| is at least the observed one.
for m in range(0, 15):
outcomes = list(itertools.product((0, 1), repeat=m))
for b in range(m + 1):
c = m - b
extreme = sum(1 for o in outcomes if abs(2 * sum(o) - m) >= abs(b - c))
assert mcnemar_test(b, c, exact=True) == Fraction(extreme, 2**m)
def test_chi_square_tail_matches_normal_tail() -> None:
# With 1 degree of freedom, P(chi2 > x) = P(|Z| > sqrt(x)) = erfc(sqrt(x / 2)).
for b, c in ((15, 5), (9, 2), (40, 61), (0, 7), (300, 250)):
x = mcnemar_statistic(b, c)
assert mcnemar_test(b, c, "asymptotic") == pytest.approx(math.erfc(math.sqrt(x / 2)), rel=1e-9, abs=1e-15)
def conditional_size(m: int, method: str) -> Fraction:
return Fraction(sum(math.comb(m, k) for k in range(m + 1) if mcnemar_test(k, m - k, method) <= 0.05), 2**m)
def test_conditional_sizes() -> None:
alpha = Fraction(1, 20)
exact = [conditional_size(m, "exact") for m in range(101)]
asymptotic = [conditional_size(m, "asymptotic") for m in range(101)]
corrected = [conditional_size(m, "corrected") for m in range(101)]
assert all(s <= alpha for s in exact) # proved
assert all(s <= alpha for s in corrected) # measured for m <= 100 only
assert asymptotic[4] == Fraction(1, 8) # rejects at b = 4, c = 0
assert sum(s > alpha for s in asymptotic) == 47
assert corrected[17] < exact[17]
def unconditional_size(n: int, pi: float, method: str) -> float:
# n pairs, each discordant with probability pi, split evenly under the null.
sizes = [float(conditional_size(m, method)) for m in range(n + 1)]
return math.fsum(math.comb(n, m) * pi**m * (1 - pi) ** (n - m) * sizes[m] for m in range(n + 1))
def test_unconditional_size_exact_and_by_simulation() -> None:
n, pi = 50, 0.2
want = {method: unconditional_size(n, pi, method) for method in METHODS}
assert want["exact"] == pytest.approx(0.02213, abs=1e-5)
assert want["asymptotic"] == pytest.approx(0.04292, abs=1e-5)
assert want["corrected"] == pytest.approx(0.02183, abs=1e-5)
assert unconditional_size(100, 0.3, "asymptotic") > 0.05
rng = random.Random(1)
reps = 10000
hits = dict.fromkeys(METHODS, 0)
for _ in range(reps):
b = c = 0
for _ in range(n):
u = rng.random()
if u < pi / 2:
b += 1
elif u < pi:
c += 1
for method in METHODS:
hits[method] += mcnemar_test(b, c, method) <= 0.05
for method in METHODS:
se = math.sqrt(want[method] * (1 - want[method]) / reps)
assert abs(hits[method] / reps - want[method]) < 4 * se
def test_symmetry_and_edges() -> None:
for b, c in ((3, 11), (0, 9), (25, 30)):
for method in METHODS:
assert mcnemar_test(b, c, method) == mcnemar_test(c, b, method)
assert mcnemar_test(0, 0) == 1.0 and mcnemar_test(0, 0, exact=True) == 1
assert mcnemar_test(7, 7, exact=True) == 1
assert mcnemar_test(7, 7, "corrected") == 1.0
assert mcnemar_test(0, 6, exact=True) == Fraction(1, 32)
assert 0 < mcnemar_test(0, 2000, exact=True) < Fraction(1, 2**1998)
def test_errors() -> None:
with pytest.raises(ValueError):
mcnemar_test(-1, 3)
with pytest.raises(ValueError):
mcnemar_test(1, 3, "wald")
with pytest.raises(ValueError):
mcnemar_test(1.5, 3) # type: ignore[arg-type]
History
Quinn McNemar (1947) derived the standard error of the difference between two correlated proportions and the statistic , with its chi-square reference. Allen L. Edwards (1948) proposed the continuity correction. The exact conditional form is the binomial sign test applied to the discordant pairs, which goes back to Arbuthnot's sign test of 1710. Bowker (1948) extended the idea to symmetry in square tables and Cochran (1950) to several matched conditions.
References
- Quinn McNemar, Note on the sampling error of the difference between correlated proportions or percentages, Psychometrika 12(2), 1947, pp. 153 to 157 (the statistic for the change between two correlated proportions)
- Allen L. Edwards, Note on the correction for continuity in testing the significance of the difference between correlated proportions, Psychometrika 13(3), 1948, the corrected statistic (|b - c| - 1)^2/(b + c)
- Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Chapter 11 (models for matched pairs, with the comparison of dependent proportions and McNemar's test)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag H919BT Edit this page History Report an error Markdown