Test for independence in two-way contingency tables

Suppose $(X_1, Y_1), \ldots, (X_n, Y_n) \sim P$ iid, with $X_1\in (1,2,\ldots,r)$ and $Y_1\in (1,2,\ldots,c)$. Test $H_0: X_1$ and $Y_1$ are independent.

Summarise data by a contingency table with entries $N_{xy} = \sum_{i=1}^{n} \mathbb{1}_{\set{X_i = x, Y_i = y}}$. Model as $$ \begin{align*} (N_{11}, \ldots, N_{1c}, \ldots, N_{r1}, \ldots, N_{rc}) \sim \mathrm{Multinomial}(n; p_{11}, \ldots, p_{1c}, \ldots, p_{r 1}, \ldots, p_{rc}). \end{align*} $$ Now

Apply Pearson's chi-squared test with $$ \begin{align*} O_{xy} = N_{xy}, \qquad E_{xy} = \frac{N_{x+} N_{+y}}{n}, \qquad d=(r-1)(c-1). \end{align*} $$ (Derivation)