Algorithm Search⌘K

Algorithmintro

Chi-squared test of independence

Also called contingency table chi-squared test, chi-squared test of association.

Tests whether two categorical variables are independent by comparing a contingency table with the product of its margins, with (r - 1)(c - 1) degrees of freedom.

Time
Θ(r·c) worst · best
Space
Θ(r·c) extra
Where
c = the number of columns; r = the number of rows
Properties
deterministicnot exactofflineiterative
Origin
Karl Pearson, Ronald A. Fisher, Frank Yates, William G. Cochran, 1900

The chi-squared test of independence checks whether two categorical variables are related, from an r×cr \times c table of counts. If the variables are independent, the count in cell (i,j)(i, j) should be close to Eij=RiCj/nE_{ij} = R_i C_j/n, the product of its row and column totals divided by the grand total. The test adds up (Oij−Eij)2/Eij(O_{ij} - E_{ij})^2/E_{ij} over all cells. Under independence and for large samples this sum has approximately the chi-square law with (r−1)(c−1)(r - 1)(c - 1) degrees of freedom.

In plain words

Give 100 patients one of two treatments and record whether each one improved, stayed the same or got worse. If the treatment makes no difference, the share of patients who improved should be about the same in both groups, and also in the whole sample. So the overall shares tell you what each cell of the table should contain. The test measures how far the real table is from that "no difference" table. The degrees of freedom count how many cells you can fill in freely once the row and column totals are fixed: (r−1)(c−1)(r - 1)(c - 1), which is 2 for a table with 2 rows and 3 columns.

The problem

Model. Three sampling schemes give the same test:

  1. nn units are sampled and classified by both variables; the table is multinomial.
  2. The row totals are fixed by design, as in a trial with set group sizes; each row is an independent multinomial sample.
  3. Both margins are fixed, as in Fisher's tea tasting experiment; the table is multiple hypergeometric under the null.

Hypotheses. H0H_0: independence, πij=πi+π+j\pi_{ij} = \pi_{i+} \pi_{+j} in scheme 1, or equal row distributions (homogeneity) in scheme 2. H1H_1: any other table of probabilities. There is no direction.

Statistic.

X2=∑i=1r∑j=1c(Oij−Eij)2Eij,Eij=RiCjn.X^2 = \sum_{i = 1}^r \sum_{j = 1}^c \frac{(O_{ij} - E_{ij})^2}{E_{ij}}, \qquad E_{ij} = \frac{R_i C_j}{n}.

The likelihood-ratio form is G=2∑ijOijlog⁡(Oij/Eij)G = 2 \sum_{ij} O_{ij} \log(O_{ij}/E_{ij}). For a 2×22 \times 2 table, Yates's corrected statistic subtracts 1/21/2 from each ∣Oij−Eij∣\lvert O_{ij} - E_{ij} \rvert (but not below 0).

Null distribution. Asymptotic: X2X^2 tends to χ(r−1)(c−1)2\chi^2_{(r - 1)(c - 1)}. The table has rc−1rc - 1 free cell probabilities, and the null fits (r−1)+(c−1)(r - 1) + (c - 1) of them from the margins, which leaves rc−1−(r−1)−(c−1)=(r−1)(c−1)rc - 1 - (r - 1) - (c - 1) = (r - 1)(c - 1).

Rejection rule and size. Reject when p≤αp \le \alpha, that is when X2≥χ((r−1)(c−1), 1−α)2X^2 \ge \chi^2_{((r - 1)(c - 1),\ 1 - \alpha)}. The size tends to α\alpha (proved for scheme 1). For finite nn it is not controlled. The exact computations below show sizes close to α\alpha even with small expected counts, and show that Yates's correction is very conservative.

P-values. p=P(χ(r−1)(c−1)2>X2)p = P(\chi^2_{(r - 1)(c - 1)} > X^2), the upper tail only.

Sensitivity and power. For a fixed dependent table the power tends to 1. For alternatives near independence, X2X^2 is approximately noncentral chi-square with noncentrality n∑ij(πij−πi+π+j)2/(πi+π+j)n \sum_{ij} (\pi_{ij} - \pi_{i+}\pi_{+j})^2/(\pi_{i+}\pi_{+j}). As with the goodness-of-fit test, the power is spread over all directions, so for ordered categories a trend test is more powerful against a trend.

The algorithm

  1. CHI-SQUARED-INDEPENDENCE(O[1..r][1..c])
  2. 1R[i] ← row totals; C[j] ← column totals; n ← total ▷ every R[i] and C[j] must be positive
  3. 2for i ← 1 to r, j ← 1 to c do
  4. 3E ← R[i] · C[j] / n
  5. 4add (O[i][j] - E)^2 / E to the sum ▷ or 2 O log(O / E); Yates: (max(0, |O - E| - 1/2))^2 / E
  6. 5X2 ← the sum
  7. 6df ← (r - 1)(c - 1)
  8. 7return (X2, df, P(χ²_df > X2))

Line L7 uses chi2_sf from the shared helper module. The code raises an error for a table with an empty row or column, because then some EijE_{ij} is 0; such a row or column carries no information about the association, and dropping it gives the right table.

Example

Treatment and outcome. One hundred patients get treatment A (40) or B (60). The outcomes are:

improved same worse total
A 20 15 5 40
B 10 20 30 60
total 30 35 35 100

The expected counts are E11=40⋅30/100=12E_{11} = 40 \cdot 30/100 = 12, and in full

improved same worse
A 12 14 14
B 18 21 21

The cell terms are 64/12=5.33364/12 = 5.333, 1/14=0.0711/14 = 0.071 and 81/14=5.78681/14 = 5.786 for A, and 64/18=3.55664/18 = 3.556, 1/21=0.0481/21 = 0.048 and 81/21=3.85781/21 = 3.857 for B. So X2=1175/63=18.651X^2 = 1175/63 = 18.651 on (2−1)(3−1)=2(2 - 1)(3 - 1) = 2 degrees of freedom, and p=8.91×10−5p = 8.91 \times 10^{-5}. The likelihood-ratio form gives G=19.900G = 19.900 and p=4.77×10−5p = 4.77 \times 10^{-5}. The adjusted residuals (Oij−Eij)/Eij(1−Ri/n)(1−Cj/n)(O_{ij} - E_{ij})/\sqrt{E_{ij}(1 - R_i/n)(1 - C_j/n)} are 3.563.56, 0.430.43 and −3.85-3.85 for row A, so the association is in the "improved" and "worse" columns: A patients improved more often and got worse less often.

A 2 x 2 table. With rows (12,5)(12, 5) and (7,16)(7, 16), n=40n = 40:

  • X2=40(12⋅16−5⋅7)2/(17⋅23⋅19⋅21)=6.320X^2 = 40(12 \cdot 16 - 5 \cdot 7)^2/(17 \cdot 23 \cdot 19 \cdot 21) = 6.320 and p=0.0119p = 0.0119.
  • This is z2z^2 for the two-proportion comparison 12/17=0.70612/17 = 0.706 against 7/23=0.3047/23 = 0.304.
  • With Yates's correction, X2=4.812X^2 = 4.812 and p=0.0283p = 0.0283.
  • The two-sided Fisher exact test gives p=0.0238p = 0.0238.

The tests check these numbers, and check X2X^2 against exact rational arithmetic for 300 random tables of up to 5×55 \times 5.

Correctness

The full proof is in proofs/correctness.md. The expected counts RiCj/nR_i C_j/n are the maximum likelihood fit of the independence model, so this is a goodness-of-fit test with (r−1)+(c−1)(r - 1) + (c - 1) fitted parameters. The proof writes the residual matrix Vij=(Oij−Eij)/nπi+π+jV_{ij} = (O_{ij} - E_{ij})/\sqrt{n \pi_{i+} \pi_{+j}} as a fixed linear map of the standardized counts plus a term that tends to 0. In the limit the linear map becomes Z↦QαZQβZ \mapsto Q_\alpha Z Q_\beta, where ZZ is a matrix of independent standard normals and QαQ_\alpha and QβQ_\beta project out the square roots of the row and column probabilities. This is an orthogonal projection of rank (r−1)(c−1)(r - 1)(c - 1), so X2=∥V∥2+oP(1)X^2 = \lVert V \rVert^2 + o_P(1) tends to χ(r−1)(c−1)2\chi^2_{(r - 1)(c - 1)}. For the 2×22 \times 2 table every cell has ∣Oij−Eij∣=∣ad−bc∣/n\lvert O_{ij} - E_{ij} \rvert = \lvert ad - bc \rvert/n, which gives the closed form above.

Proof: Under independence the Pearson statistic with expected counts from the margins tends to chi-square with (r - 1)(c - 1) degrees of freedomfull

Model. nn independent units are classified by a row variable with r≥2r \ge 2 levels and a column variable with c≥2c \ge 2 levels. Cell (i,j)(i, j) has probability πij\pi_{ij}, and the counts OijO_{ij} are multinomial. Write RiR_i and CjC_j for the row and column totals. The null hypothesis of independence is πij=aibj\pi_{ij} = a_i b_j for all i,ji, j, where ai>0a_i > 0 and bj>0b_j > 0 are the marginal probabilities. The expected counts are Eij=RiCj/nE_{ij} = R_i C_j/n, and

X2=∑i,j(Oij−Eij)2Eij.X^2 = \sum_{i, j} \frac{(O_{ij} - E_{ij})^2}{E_{ij}}.

Claim 1 (lines L1 to L7 compute the statistic). Line L1 forms the row totals, the column totals and nn. Lines L2 and L3 visit every cell and form Eij=RiCj/nE_{ij} = R_i C_j/n, which is positive because the code rejects a table with an empty row or column. Line L4 adds the cell's term: (Oij−Eij)2/Eij(O_{ij} - E_{ij})^2/E_{ij}, or (max⁡(0,∣Oij−Eij∣−12))2/Eij(\max(0, \lvert O_{ij} - E_{ij} \rvert - \tfrac12))^2/E_{ij} with the Yates correction, or 2Oijlog⁡(Oij/Eij)2 O_{ij} \log(O_{ij}/E_{ij}) for GG (zero when Oij=0O_{ij} = 0). Line L5 sums the terms with math.fsum, line L6 sets df=(r−1)(c−1)\mathrm{df} = (r - 1)(c - 1), and line L7 returns the upper tail P(χdf2>X2)P(\chi^2_{\mathrm{df}} > X^2) from the regularized incomplete gamma function. □\square

The value Eij=RiCj/nE_{ij} = R_i C_j/n is na^ib^jn \hat a_i \hat b_j, where a^i=Ri/n\hat a_i = R_i/n and b^j=Cj/n\hat b_j = C_j/n are the maximum likelihood estimates of the margins under independence. (The log-likelihood ∑ijOij(log⁡ai+log⁡bj)=∑iRilog⁡ai+∑jCjlog⁡bj\sum_{ij} O_{ij} (\log a_i + \log b_j) = \sum_i R_i \log a_i + \sum_j C_j \log b_j separates, and each part is maximized by the observed proportions.) So the test is the goodness-of-fit test of the family {aibj}\{a_i b_j\}, which has (r−1)+(c−1)(r - 1) + (c - 1) free parameters, fitted from the counts.

Claim 2 (the limit law). Under H0H_0, with aa and bb fixed and n→∞n \to \infty, X2X^2 converges in distribution to χ(r−1)(c−1)2\chi^2_{(r - 1)(c - 1)}.

Proof. Put αi=ai\alpha_i = \sqrt{a_i} and βj=bj\beta_j = \sqrt{b_j}. Then ∥α∥=∥β∥=1\lVert \alpha \rVert = \lVert \beta \rVert = 1. Treat r×cr \times c arrays as matrices and use the Frobenius norm ∥A∥2=∑ijAij2\lVert A \rVert^2 = \sum_{ij} A_{ij}^2.

Step 1: the standardized counts. Let δij=Oij−naibj\delta_{ij} = O_{ij} - n a_i b_j and Uij=δij/naibjU_{ij} = \delta_{ij}/\sqrt{n a_i b_j}. The cell counts are multinomial with probabilities aibja_i b_j, so the argument of the goodness-of-fit proof (the counts are a sum of nn iid unit vectors, and the multivariate central limit theorem applies) gives U→N(0,I−uu⊤)U \to N(0, I - u u^\top) in distribution, where u=vec⁡(αβ⊤)u = \operatorname{vec}(\alpha \beta^\top), a unit vector. Equivalently, U→Z−⟨αβ⊤,Z⟩ αβ⊤U \to Z - \langle \alpha\beta^\top, Z \rangle\, \alpha \beta^\top in distribution, where ZZ is an r×cr \times c matrix of iid standard normals and ⟨A,B⟩=∑ijAijBij\langle A, B \rangle = \sum_{ij} A_{ij} B_{ij}. Note ⟨αβ⊤,Z⟩=α⊤Zβ\langle \alpha\beta^\top, Z \rangle = \alpha^\top Z \beta.

Step 2: the residuals are a linear map of UU. Let δi⋅=Ri−nai=∑jδij\delta_{i\cdot} = R_i - n a_i = \sum_j \delta_{ij} and δ⋅j=Cj−nbj=∑iδij\delta_{\cdot j} = C_j - n b_j = \sum_i \delta_{ij}. Then

Eij=(nai+δi⋅)(nbj+δ⋅j)n=naibj+aiδ⋅j+bjδi⋅+δi⋅δ⋅jn.E_{ij} = \frac{(n a_i + \delta_{i\cdot})(n b_j + \delta_{\cdot j})}{n} = n a_i b_j + a_i \delta_{\cdot j} + b_j \delta_{i\cdot} + \frac{\delta_{i\cdot} \delta_{\cdot j}}{n}.

Let Vij=(Oij−Eij)/naibjV_{ij} = (O_{ij} - E_{ij})/\sqrt{n a_i b_j}. Dividing term by term, and using δ⋅j/n=∑kαkβjUkj\delta_{\cdot j}/\sqrt n = \sum_k \alpha_k \beta_j U_{kj} and δi⋅/n=∑lαiβlUil\delta_{i\cdot}/\sqrt n = \sum_l \alpha_i \beta_l U_{il},

V=U−αα⊤U−Uββ⊤−Wn,Wn,ij=δi⋅δ⋅jnnaibj.V = U - \alpha \alpha^\top U - U \beta \beta^\top - W_n, \qquad W_{n, ij} = \frac{\delta_{i\cdot} \delta_{\cdot j}}{n \sqrt{n a_i b_j}}.

Each δi⋅/n\delta_{i\cdot}/\sqrt n and δ⋅j/n\delta_{\cdot j}/\sqrt n is bounded in probability (they are linear in UU), so Wn=OP(n−1/2)W_n = O_P(n^{-1/2}).

Step 3: the limit of the residuals. Let L(U)=U−αα⊤U−Uββ⊤L(U) = U - \alpha\alpha^\top U - U \beta\beta^\top, a fixed linear map. By Step 1, the continuous mapping theorem and Slutsky's theorem, V→L(U∞)V \to L(U_\infty) in distribution with U∞=Z−(α⊤Zβ) αβ⊤U_\infty = Z - (\alpha^\top Z \beta)\, \alpha\beta^\top. Write Pα=αα⊤P_\alpha = \alpha\alpha^\top, Qα=I−PαQ_\alpha = I - P_\alpha, and the same for β\beta. A direct expansion gives L(U)=QαUQβ−PαUPβL(U) = Q_\alpha U Q_\beta - P_\alpha U P_\beta. For U=U∞U = U_\infty:

  • PαU∞Pβ=(α⊤U∞β) αβ⊤P_\alpha U_\infty P_\beta = (\alpha^\top U_\infty \beta)\, \alpha\beta^\top and α⊤U∞β=α⊤Zβ−(α⊤Zβ)∥α∥2∥β∥2=0\alpha^\top U_\infty \beta = \alpha^\top Z \beta - (\alpha^\top Z \beta) \lVert\alpha\rVert^2 \lVert\beta\rVert^2 = 0;
  • QαU∞Qβ=QαZQβ−(α⊤Zβ) (Qαα)(Qββ)⊤=QαZQβQ_\alpha U_\infty Q_\beta = Q_\alpha Z Q_\beta - (\alpha^\top Z \beta)\, (Q_\alpha \alpha)(Q_\beta \beta)^\top = Q_\alpha Z Q_\beta, because Qαα=0Q_\alpha \alpha = 0.

So V→QαZQβV \to Q_\alpha Z Q_\beta in distribution.

Step 4: the law of the limit. The map Z↦QαZQβZ \mapsto Q_\alpha Z Q_\beta is linear, symmetric for the inner product ⟨⋅,⋅⟩\langle \cdot, \cdot \rangle, and idempotent, so it is an orthogonal projection on the space of r×cr \times c matrices. Its range is the set of matrices whose columns are orthogonal to α\alpha and whose rows are orthogonal to β\beta. Taking orthonormal bases α,g2,…,gr\alpha, g_2, \ldots, g_r of Rr\mathbb{R}^r and β,h2,…,hc\beta, h_2, \ldots, h_c of Rc\mathbb{R}^c, the matrices gkhl⊤g_k h_l^\top with k,l≥2k, l \ge 2 form an orthonormal basis of that range, so it has dimension (r−1)(c−1)(r - 1)(c - 1). As in the goodness-of-fit proof, the squared norm of the projection of a standard normal vector onto a subspace of dimension dd is a sum of dd squared iid standard normals, so ∥QαZQβ∥2∼χ(r−1)(c−1)2\lVert Q_\alpha Z Q_\beta \rVert^2 \sim \chi^2_{(r - 1)(c - 1)}.

Step 5: the statistic. X2=∑ijVij2⋅naibj/EijX^2 = \sum_{ij} V_{ij}^2 \cdot n a_i b_j/E_{ij}. By the law of large numbers, Eij/(naibj)=a^ib^j/(aibj)→1E_{ij}/(n a_i b_j) = \hat a_i \hat b_j/(a_i b_j) \to 1 in probability, so X2=∥V∥2+oP(1)X^2 = \lVert V \rVert^2 + o_P(1), and by Step 3, Step 4 and the continuous mapping theorem, X2→χ(r−1)(c−1)2X^2 \to \chi^2_{(r - 1)(c - 1)} in distribution. □\square

Claim 3 (the size). For fixed α∈(0,1)\alpha \in (0, 1) the size of the test that rejects when p≤αp \le \alpha tends to α\alpha, because the limit law is continuous and the p-value is a strictly decreasing function of X2X^2. □\square

Claim 4 (the 2 x 2 table). For the table with rows (a,b)(a, b) and (c,d)(c, d), row totals r1,r2r_1, r_2, column totals c1,c2c_1, c_2 and n=r1+r2n = r_1 + r_2:

  1. X2=n(ad−bc)2/(r1r2c1c2)X^2 = n(ad - bc)^2/(r_1 r_2 c_1 c_2).
  2. X2=z2X^2 = z^2, where z=(p^1−p^2)/p^(1−p^)(1/r1+1/r2)z = (\hat p_1 - \hat p_2)/\sqrt{\hat p (1 - \hat p)(1/r_1 + 1/r_2)} is the pooled two-proportion statistic, with p^1=a/r1\hat p_1 = a/r_1, p^2=c/r2\hat p_2 = c/r_2 and p^=c1/n\hat p = c_1/n.
  3. The Yates statistic is n(max⁡(0,∣ad−bc∣−n/2))2/(r1r2c1c2)n(\max(0, \lvert ad - bc \rvert - n/2))^2/(r_1 r_2 c_1 c_2).

Proof. O11−E11=a−r1c1/n=(a(a+b+c+d)−(a+b)(a+c))/n=(ad−bc)/nO_{11} - E_{11} = a - r_1 c_1/n = (a(a + b + c + d) - (a + b)(a + c))/n = (ad - bc)/n. The margins of O−EO - E are zero, so in a 2×22 \times 2 table every cell has ∣Oij−Eij∣=∣ad−bc∣/n\lvert O_{ij} - E_{ij} \rvert = \lvert ad - bc \rvert/n. Also ∑ij1/Eij=n (r1+r2)(c1+c2)/(r1r2c1c2)=n3/(r1r2c1c2)\sum_{ij} 1/E_{ij} = n\,(r_1 + r_2)(c_1 + c_2)/(r_1 r_2 c_1 c_2) = n^3/(r_1 r_2 c_1 c_2). Multiplying gives part 1, and with ∣ad−bc∣/n−1/2\lvert ad - bc \rvert/n - 1/2 in place of ∣ad−bc∣/n\lvert ad - bc \rvert/n it gives part 3. For part 2, p^1−p^2=(ar2−cr1)/(r1r2)=(ad−bc)/(r1r2)\hat p_1 - \hat p_2 = (a r_2 - c r_1)/(r_1 r_2) = (ad - bc)/(r_1 r_2) and p^(1−p^)(1/r1+1/r2)=c1c2/(nr1r2)\hat p(1 - \hat p)(1/r_1 + 1/r_2) = c_1 c_2/(n r_1 r_2), so z2=n(ad−bc)2/(r1r2c1c2)z^2 = n(ad - bc)^2/(r_1 r_2 c_1 c_2). □\square

Part 1 shows that, given all four margins, X2X^2 is an increasing function of ∣a−r1c1/n∣\lvert a - r_1 c_1/n \rvert. Given the margins, aa is hypergeometric under the null, so the chi-squared test of a 2×22 \times 2 table approximates a two-sided Fisher exact test that orders the tables by their distance from the expected count.

Other sampling schemes (cited). With the row totals fixed in advance (independent multinomial samples, one per row), the null hypothesis is that the rows have the same distribution, and X2X^2 has the same χ(r−1)(c−1)2\chi^2_{(r - 1)(c - 1)} limit. The same holds when both margins are fixed, by the limit of the multiple hypergeometric law. Agresti's book treats both cases. For r=c=2r = c = 2 with fixed rows, part 2 of Claim 4 gives the limit directly from the normal limit of the two-proportion statistic.

The G statistic. The Taylor bound of the goodness-of-fit proof, applied with EijE_{ij} in place of EiE_i and dij=Oij−Eij=OP(n)d_{ij} = O_{ij} - E_{ij} = O_P(\sqrt n) with ∑ijdij=0\sum_{ij} d_{ij} = 0, gives G−X2=OP(n−1/2)G - X^2 = O_P(n^{-1/2}), so GG has the same limit.

Cost. Line L1 takes Θ(rc)\Theta(rc) additions. Lines L2 to L4 do Θ(1)\Theta(1) work per cell, so Θ(rc)\Theta(rc) in all. The code keeps the rcrc terms for the exact summation in line L5, so it uses Θ(rc)\Theta(rc) extra space; a running sum would use Θ(r+c)\Theta(r + c) for the margins. Line L7 is one incomplete gamma evaluation.

Complexity

The margins take Θ(rc)\Theta(rc) additions and the statistic takes Θ(1)\Theta(1) work per cell, so the time is Θ(rc)\Theta(rc). The code keeps the rcrc terms for an exactly rounded sum, so it uses Θ(rc)\Theta(rc) extra space; a running sum needs only Θ(r+c)\Theta(r + c) for the margins. The p-value is one incomplete gamma evaluation.

Properties

  • Size for small samples (computed exactly). Under multinomial sampling with independent variables, summing over all tables gives the true size at α=0.05\alpha = 0.05. A table with an empty row or column has no test and counts as not rejected.

    table nn margins smallest expected count size of X2X^2 size with Yates
    2×22 \times 2 20 (0.5,0.5)(0.5, 0.5) and (0.5,0.5)(0.5, 0.5) 5 0.0512 0.0128
    2×22 \times 2 40 (0.5,0.5)(0.5, 0.5) and (0.5,0.5)(0.5, 0.5) 10 0.0508 0.0206
    2×22 \times 2 40 (0.8,0.2)(0.8, 0.2) and (0.8,0.2)(0.8, 0.2) 1.6 0.0417
    2×32 \times 3 15 (0.4,0.6)(0.4, 0.6) and (0.2,0.3,0.5)(0.2, 0.3, 0.5) 1.2 0.0420

    The tests compute these values and check the last one against a simulation (seed 6, 20000 tables).

  • Yates's correction is conservative. It brings the statistic close to the conditional exact test, which is itself conservative under multinomial sampling, so it loses power. Many authors now advise against it.

  • Symmetric. Transposing the table, or permuting its rows or columns, does not change X2X^2.

  • Scales with nn. Multiplying every count by mm multiplies X2X^2 by mm. So X2X^2 measures evidence, not the strength of the association. Cramér's V=X2/(nmin⁡(r−1,c−1))V = \sqrt{X^2/(n \min(r - 1, c - 1))} is a measure of strength; it is 0.4320.432 in the treatment example.

  • The 2 x 2 test is the two-proportion z test. X2=z2X^2 = z^2 for the pooled two-proportion statistic, so the two-sided tests are the same.

Variants and improvements

  • Fisher's exact test. For a 2×22 \times 2 table with small counts, the Fisher exact test conditions on both margins and has size at most α\alpha. The Freeman-Halton extension does the same for r×cr \times c tables.
  • Monte Carlo and permutation p-values. Fix both margins, draw random tables with those margins (by permuting one variable against the other), and compare X2X^2 with the simulated values, as in a permutation test.
  • Likelihood-ratio statistic GG. The code computes it with statistic="g". It splits into parts for nested tables, which is the basis of log-linear models.
  • Ordered categories. The Cochran-Armitage trend test and the linear-by-linear association test use one degree of freedom and have more power against a trend.
  • Stratified tables. With a third variable, the Cochran-Mantel-Haenszel test combines 2×22 \times 2 tables across strata.
  • Paired data. For the same units measured twice, use McNemar's test, not this test.

When to use it

Use it to test association between two unordered categorical variables from independent units, when most expected counts are not tiny. Cochran's rule (no expected count below 1, and at most 20% of them below 5) is a common guide, and the exact sizes above show that the Pearson statistic does well even near those limits. For 2×22 \times 2 tables with small counts, or whenever an exact level is needed, use Fisher's exact test or a Monte Carlo p-value.

Pitfalls

  • Units that are not independent. Repeated measurements on the same subjects, or several answers from one person, break the multinomial model. For two measurements on the same units, use McNemar's test.
  • Percentages instead of counts. The test needs counts. Percentages change nn.
  • Reading X2X^2 or pp as the strength of the association. A tiny p-value with a large nn can come from a very weak association. Report a measure such as a difference of proportions, an odds ratio or Cramér's VV.
  • Merging categories after seeing the data. Choosing which cells to combine to get significance changes the null law.
  • Simpson's paradox. An association in the combined table can reverse inside each level of a third variable. Stratify when a confounder is known.
  • Expecting the test to say which cells matter. A significant result says only that the table is not independent. Look at the adjusted residuals.

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.

chi_squared_independence.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-test-of-independence/. The authors are listed in prov/E5V169.jsonl.

import math
from collections.abc import Sequence

from stdist import chi2_sf


def chi_squared_independence(
    table: Sequence[Sequence[int]],
    statistic: str = "pearson",
    yates: bool = False,
) -> tuple[float, int, float]:
    """Pearson's chi-squared test of independence for an r x c contingency table.

    The expected count of cell (i, j) is (row total i)(column total j)/n.
    statistic "pearson" gives X^2 = sum (O - E)^2 / E; "g" gives the
    likelihood-ratio statistic G = 2 sum O log(O / E). yates=True applies
    Yates's continuity correction, (|O - E| - 1/2)^2 / E with |O - E| - 1/2
    floored at 0, and is allowed only for a 2 x 2 table with statistic "pearson".
    Returns (statistic, (r - 1)(c - 1), upper chi-square tail p-value).
    """
    r = len(table)
    if r < 2 or any(len(row) != len(table[0]) for row in table) or len(table[0]) < 2:
        raise ValueError("need a rectangular table with at least two rows and two columns")
    if any(not isinstance(o, int) or o < 0 for row in table for o in row):
        raise ValueError("counts must be non-negative integers")
    if statistic not in ("pearson", "g"):
        raise ValueError("unknown statistic")
    c = len(table[0])
    if yates and (r, c, statistic) != (2, 2, "pearson"):
        raise ValueError("the Yates correction is for the Pearson statistic of a 2 x 2 table")
    rows = [sum(row) for row in table]  # @line L1
    cols = [sum(table[i][j] for i in range(r)) for j in range(c)]
    n = sum(rows)
    if min(rows) == 0 or min(cols) == 0:
        raise ValueError("every row and column total must be positive")
    terms = []
    for i in range(r):  # @line L2
        for j in range(c):
            o, e = table[i][j], rows[i] * cols[j] / n  # @line L3
            if statistic == "g":  # @line L4
                if o > 0:
                    terms.append(2.0 * o * math.log(o * n / (rows[i] * cols[j])))
            else:
                d = abs(o - e)
                if yates:
                    d = max(0.0, d - 0.5)
                terms.append(d * d / e)
    x2 = math.fsum(terms)  # @line L5
    df = (r - 1) * (c - 1)  # @line L6
    return x2, df, chi2_sf(x2, df)  # @line L7
chi_squared_test_of_independence.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-test-of-independence/. The authors are listed in prov/E5V169.jsonl.

"""Entry point named after the slug. The code lives in chi_squared_independence.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from chi_squared_independence import chi_squared_independence

__all__ = ["chi_squared_independence"]
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)
test_chi_squared_test_of_independence.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-test-of-independence/. The authors are listed in prov/E5V169.jsonl.

import math
import random
from fractions import Fraction

import pytest

from chi_squared_test_of_independence import chi_squared_independence

TREATMENT = [[20, 15, 5], [10, 20, 30]]


def exact_pearson(table: list[list[int]]) -> Fraction:
    rows = [sum(row) for row in table]
    cols = [sum(col) for col in zip(*table)]
    n = sum(rows)
    return sum(
        (Fraction(table[i][j]) - Fraction(rows[i] * cols[j], n)) ** 2 / Fraction(rows[i] * cols[j], n)
        for i in range(len(rows))
        for j in range(len(cols))
    )


def compositions(n: int, k: int):
    if k == 1:
        yield (n,)
        return
    for first in range(n + 1):
        for rest in compositions(n - first, k - 1):
            yield (first, *rest)


def multinomial_pmf(counts: tuple[int, ...], probs: list[float]) -> float:
    coef = math.factorial(sum(counts))
    for c in counts:
        coef //= math.factorial(c)
    return coef * math.prod(p**c for p, c in zip(probs, counts))


def rejects(table: list[list[int]], **kw) -> bool:
    # A table with an empty row or column has no test; count it as not rejected.
    try:
        return chi_squared_independence(table, **kw)[2] <= 0.05
    except ValueError:
        return False


def exact_size(n: int, pr: list[float], pc: list[float], **kw) -> float:
    r, c = len(pr), len(pc)
    w = [pr[i] * pc[j] for i in range(r) for j in range(c)]
    total = 0.0
    for cnt in compositions(n, r * c):
        if rejects([list(cnt[i * c : (i + 1) * c]) for i in range(r)], **kw):
            total += multinomial_pmf(cnt, w)
    return total


def test_page_examples() -> None:
    x2, df, p = chi_squared_independence(TREATMENT)
    assert (df, x2) == (2, pytest.approx(18.650794, abs=1e-6))
    assert p == pytest.approx(8.9132e-05, rel=1e-4)
    g2, df, p = chi_squared_independence(TREATMENT, statistic="g")
    assert (df, g2) == (2, pytest.approx(19.899774, abs=1e-6))
    assert p == pytest.approx(4.7733e-05, rel=1e-4)
    x2, df, p = chi_squared_independence([[12, 5], [7, 16]])
    assert (df, x2, p) == (1, pytest.approx(6.319892, abs=1e-6), pytest.approx(0.011939, abs=1e-6))
    x2, df, p = chi_squared_independence([[12, 5], [7, 16]], yates=True)
    assert (x2, p) == (pytest.approx(4.812286, abs=1e-6), pytest.approx(0.028258, abs=1e-6))


def test_statistic_against_fractions() -> None:
    assert exact_pearson(TREATMENT) == Fraction(1175, 63)
    rng = random.Random(3)
    for _ in range(300):
        r, c = rng.randint(2, 5), rng.randint(2, 5)
        table = [[rng.randint(0, 30) for _ in range(c)] for _ in range(r)]
        if min(map(sum, table)) == 0 or min(map(sum, zip(*table))) == 0:
            continue
        x2, df, _ = chi_squared_independence(table)
        assert df == (r - 1) * (c - 1)
        assert x2 == pytest.approx(float(exact_pearson(table)), rel=1e-12, abs=1e-12)


def test_two_by_two_closed_forms() -> None:
    rng = random.Random(4)
    for _ in range(300):
        a, b, c, d = (rng.randint(0, 25) for _ in range(4))
        r1, r2, c1, c2 = a + b, c + d, a + c, b + d
        if 0 in (r1, r2, c1, c2):
            continue
        n = r1 + r2
        den = r1 * r2 * c1 * c2
        x2 = chi_squared_independence([[a, b], [c, d]])[0]
        assert x2 == pytest.approx(n * (a * d - b * c) ** 2 / den, rel=1e-12, abs=1e-12)
        # The square of the pooled two-proportion z statistic.
        p1, p2, pooled = a / r1, c / r2, c1 / n
        z = (p1 - p2) / math.sqrt(pooled * (1 - pooled) * (1 / r1 + 1 / r2))
        assert x2 == pytest.approx(z * z, rel=1e-9, abs=1e-12)
        yates = chi_squared_independence([[a, b], [c, d]], yates=True)[0]
        excess = max(0.0, abs(a * d - b * c) - n / 2)
        assert yates == pytest.approx(n * excess**2 / den, rel=1e-12, abs=1e-12)


def test_one_degree_of_freedom_tail() -> None:
    for table in ([[12, 5], [7, 16]], [[40, 10], [30, 20]], [[3, 9], [8, 1]]):
        x2, _, p = chi_squared_independence(table)
        assert p == pytest.approx(math.erfc(math.sqrt(x2 / 2)), rel=1e-9)


def test_invariance() -> None:
    rng = random.Random(5)
    for _ in range(100):
        table = [[rng.randint(1, 20) for _ in range(4)] for _ in range(3)]
        base = chi_squared_independence(table)
        transposed = [list(col) for col in zip(*table)]
        assert chi_squared_independence(transposed)[0] == pytest.approx(base[0], rel=1e-12)
        shuffled = [row[:] for row in table]
        rng.shuffle(shuffled)
        order = list(range(4))
        rng.shuffle(order)
        shuffled = [[row[j] for j in order] for row in shuffled]
        assert chi_squared_independence(shuffled)[0] == pytest.approx(base[0], rel=1e-12)
        scaled = [[3 * o for o in row] for row in table]
        assert chi_squared_independence(scaled)[0] == pytest.approx(3 * base[0], rel=1e-12)
    # A table equal to the product of its margins gives X^2 = 0 and p = 1.
    x2, _, p = chi_squared_independence([[2, 4, 6], [3, 6, 9]])
    assert x2 == pytest.approx(0.0, abs=1e-12)
    assert p == pytest.approx(1.0)


def test_exact_size_by_enumeration() -> None:
    # Multinomial sampling of n units with independent row and column variables.
    assert exact_size(20, [0.5, 0.5], [0.5, 0.5]) == pytest.approx(0.051201, abs=1e-6)
    assert exact_size(40, [0.5, 0.5], [0.5, 0.5]) == pytest.approx(0.050821, abs=1e-6)
    assert exact_size(20, [0.5, 0.5], [0.5, 0.5], yates=True) == pytest.approx(0.012779, abs=1e-6)
    assert exact_size(40, [0.5, 0.5], [0.5, 0.5], yates=True) == pytest.approx(0.020629, abs=1e-6)
    assert exact_size(40, [0.8, 0.2], [0.8, 0.2]) == pytest.approx(0.041699, abs=1e-6)
    assert exact_size(15, [0.4, 0.6], [0.2, 0.3, 0.5]) == pytest.approx(0.041959, abs=1e-6)


def test_enumeration_against_brute_force_sampling() -> None:
    rng = random.Random(6)
    pr, pc = [0.4, 0.6], [0.2, 0.3, 0.5]
    cells = [(i, j) for i in range(2) for j in range(3)]
    weights = [pr[i] * pc[j] for i, j in cells]
    runs, rejected = 20000, 0
    for _ in range(runs):
        table = [[0, 0, 0], [0, 0, 0]]
        for i, j in rng.choices(cells, weights, k=15):
            table[i][j] += 1
        rejected += rejects(table)
    size = exact_size(15, pr, pc)
    assert abs(rejected / runs - size) < 4 * math.sqrt(size * (1 - size) / runs)


def test_errors() -> None:
    with pytest.raises(ValueError):
        chi_squared_independence([[1, 2]])
    with pytest.raises(ValueError):
        chi_squared_independence([[1, 2], [3]])
    with pytest.raises(ValueError):
        chi_squared_independence([[1, -2], [3, 4]])
    with pytest.raises(ValueError):
        chi_squared_independence([[0, 0], [3, 4]])
    with pytest.raises(ValueError):
        chi_squared_independence([[1, 2, 3], [3, 4, 5]], yates=True)
    with pytest.raises(ValueError):
        chi_squared_independence([[1, 2], [3, 4]], statistic="z")

History

Karl Pearson published the X2X^2 statistic in 1900 and applied it to contingency tables in 1904. He used rc−1rc - 1 degrees of freedom. In 1922 Ronald Fisher showed that the expected counts use the margins, which removes (r−1)+(c−1)(r - 1) + (c - 1) degrees of freedom and leaves (r−1)(c−1)(r - 1)(c - 1); Pearson did not accept this at first. Frank Yates (1934) proposed the continuity correction for 2×22 \times 2 tables, and Fisher (1935) gave the exact conditional test. William Cochran (1952, 1954) reviewed the test and gave the rules for small expected counts that are still in common use.

References

  1. Ronald A. Fisher, On the interpretation of χ² from contingency tables, and the calculation of P, Journal of the Royal Statistical Society 85(1), 1922, pp. 87 to 94 (the degrees of freedom of a contingency table)
  2. Karl Pearson, On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling, Philosophical Magazine, series 5, 50(302), 1900, pp. 157 to 175 (the statistic)
  3. William G. Cochran, Some methods for strengthening the common χ² tests, Biometrics 10(4), 1954, the recommendations on the smallest expected counts
  4. Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Chapter 3 (inference for two-way contingency tables, with the sampling schemes and residuals)

Where this leads

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example