Exact conditional Pearson test for a binary contingency table (source code)

= Exact conditional Pearson test for a binary contingency table
{title2=$P(X=x\mid K)=\frac{\prod_i\binom{n_i}{x_i}}{\binom{N}{K}}$}

Consider independent <binomial counts> $X_i\sim\operatorname{Bin}(n_i,p)$ under the common-probability <null hypothesis>, with fixed positive row sizes $n_i$. Let $N=\sum_i n_i$, $K=\sum_i X_i$ and assume $0<K<N$. Conditional on $K$, the <probability mass function> is the displayed <multivariate hypergeometric distribution>: in the joint likelihood, the factor $p^K(1-p)^{N-K}$ is common to all admissible tables and cancels. The <Vandermonde identity> gives the denominator, so the conditional distribution is free of the unknown <nuisance parameter> $p$.

For a table $x$, its <Pearson chi-squared statistic> is
$$
Q(x)=\sum_i\frac{(Nx_i-n_iK)^2}{n_iK(N-K)}.
$$
An exact conditional <p-value> sums the displayed probabilities over all tables with the same margins and $Q(x)\ge Q(x_{\rm obs})$. The ordering is by the <Pearson chi-squared statistic>, rather than by the probability of an individual table; different exact-test orderings can give different answers. Enumeration is practical when $K$ and the number of rows are small. <Monte Carlo tests> can approximate the same tail by sampling tables with fixed margins.<Pearson's Chi-squared Test for Count Data in the R documentation>[Details: simulated contingency-table tests sample tables with fixed marginals and use the Pearson statistic]{ref}

An exact arithmetic comparison is easy too. Let $M$ be the <least common multiple> of the row sizes. Compare the <integer>
$$
A(x)=\sum_i(Nx_i-n_iK)^2\frac{M}{n_i},
$$
since every table has the same positive denominator $MK(N-K)$. This includes boundary ties without a floating-point tolerance. Conditional <p-values> are discrete and can be conservative; “exact” concerns their null calibration, not equality of rejection probability with every chosen <significance level>.