Skip to content

EProportions · Guide test 057

Pearson chi square independence test

Tests whether two categorical variables are independent in a contingency table.

Runs in CodeSplashPython example validatedR example validated

Do it in CodeSplash

In the app, set it up in Analyze with this method:

In χ² test of independence, choose Question = Independence (one sample).

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Pearson χ² test of independence

150
0.35

0 = rows and columns independent.

0.050

Your data

Edit the counts
LowMidHighTotal
Row A
28E = 22.1
20E = 17.8
24E = 32.2
72
Row B
18E = 23.9
17E = 19.2
43E = 34.8
78
Total463767150

E is the count expected if rows and columns were unrelated.

If H₀ were true

χ² = 7.58
  1. The reference: how χ² varies across samples when H₀ is true (χ² approximation).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .023).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

χ2=∑i,j(Oij−Eij)2Eij,Eij=Ri CjN\chi^2 = \sum_{i,j} \dfrac{(O_{ij}-E_{ij})^2}{E_{ij}},\qquad E_{ij} = \dfrac{R_i\, C_j}{N}

With your numbers

χ2=7.58,ν=2,min⁡E=17.76\chi^2 = 7.58,\qquad \nu = 2,\qquad \min E = 17.76
OijO_{ij}
observed count in cell (i, j)
EijE_{ij}
the count expected if rows and columns were independent
ν=(r−1)(c−1)\nu = (r-1)(c-1)
degrees of freedom

The verdict

χ²(2) = 7.58, p = .023, V = 0.22

p ≤ α = .050: reject H₀

Effect size: Cramér's V V = 0.225

Each cell contributes its squared surprise relative to independence. Check the smallest expected count: below about 5 the χ² approximation weakens.

Statistic
7.577
p-value
0.0226
Pearson χ² test of independence on a 2 × 3 table of 150 counts: χ²(2) = 7.58, p = .023, V = 0.22. The p-value is below α = .050, so the data are hard to reconcile with H0.

Pearson χ² test of independence on a 2 × 3 table of 150 counts: χ²(2) = 7.58, p = .023, V = 0.22. The p-value is below α = .050, so the data are hard to reconcile with H₀.

Question and hypotheses

H0: two categorical variables are independent.

Assumptions

Independent sampled units, mutually exclusive categories, multinomial sampling and adequate expected counts.

Formula

X2=∑ij(Oij−Eij)2EijEij=Oi+O+jN\begin{gathered}X^2=\sum_{ij}\frac{(O_{ij}-E_{ij})^2}{E_{ij}}\\[5pt] E_{ij}=\frac{O_{i+}O_{+j}}N\end{gathered}

Parameters and notation

O is an r×c table; N total count; df=(r−1)(c−1) for an unrestricted table.

Structure of the method

Build a contingency table from independent observational units, fit expected counts from row and column marginals, and aggregate squared standardized cell residuals. Under ordinary unrestricted independence, the asymptotic reference has (r-1)(c-1) degrees of freedom; the sampling design determines valid simulation alternatives.

Estimated and nuisance parameters

Estimated nuisance quantities are the row and column probability vectors under independence. Expected cells are derived from those margins. Cell labels and allowable combinations are design information; structural zeros are constraints, not small observed counts to be filled with an arbitrary constant.

Settings and design choices

Specify category definitions, missing-value handling, alpha, and any 2-by-2 continuity correction. Combining categories after observing significance changes the analysis. A Monte Carlo option needs a stated conditional or unconditional null generator, replicate count, and random seed.

Fitting and adaptation

Rebuild the table and refit its marginals for each independent dataset. In a parametric bootstrap, simulate under fitted independence and refit expectations in every replicate. Fixed-margin simulation instead conditions on both margins; it addresses a related conditional experiment and should be labeled.

Sensitivity and robustness

Inspect the smallest expected counts and residual contributions rather than invoking a universal sample-size threshold. Large sparse tables can have poor chi-square calibration. Clustered, survey-weighted, or repeated units require design-aware methods. Follow-up cell interpretation entails additional comparisons.

How to use and calibrate

Use the upper chi square tail or a sampling design appropriate exact/Monte Carlo test.

Example application

Assess association between region and product preference.

Interpretation and pitfalls

Watch out

Structural zeros and fitted constraints change degrees of freedom. Expected, not observed, counts govern approximation quality.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.

Python and R

For McNemar the table represents paired before/after categories; other entries use independent observations. The same numbers illustrate different sampling designs.

Python · native

Validated — Executed successfully in the validation environment · needs numpy, scipy

import numpy as np
from scipy import stats
rng = np.random.default_rng(2026)
tab = np.array([[18,12],[9,21]])
print(stats.chi2_contingency(tab,correction=False))
Output
Chi2ContingencyResult(statistic=np.float64(5.454545454545455), pvalue=np.float64(0.01951748118217779), dof=1, expected_freq=array([[13.5, 16.5],
       [13.5, 16.5]]))
R

Validated — Executed successfully in the validation environment · needs Base/standard library

tab <- matrix(c(18,12,9,21),nrow=2,byrow=TRUE)
print(chisq.test(tab,correct=FALSE))
Output
	Pearson's Chi-squared test

data:  tab
X-squared = 5.4545, df = 1, p-value = 0.01952

Sources

Statistics guide v4 (historical):
R: Executed successfully in the validation environment
Reference's record:
Edition 2 review: Python: executed · R: not executed (Rscript unavailable). Python: Ran in the reference's review, on this exact code. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 057, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT057.