Solution (source code)

= Solution

For a two-way <contingency table>, Pearson's statistic is
$$
\boxed{X^2=\sum_{i,j}\frac{(O_{ij}-E_{ij})^2}{E_{ij}},\qquad E_{ij}=\frac{O_{i+}O_{+j}}{N}}.
$$
Here $O_{i+},O_{+j}$ are the observed margins and $N$ their grand total. Under the <independence> null, its usual large-sample reference distribution has $(r-1)(c-1)$ <degrees of freedom> for an $r$-by-$c$ table.