EProportions · Guide test 057
Pearson chi square independence test
Tests whether two categorical variables are independent in a contingency table.
Do it in CodeSplash
In the app, set it up in Analyze with this method:
- χ² test of independence — Are two categorical variables associated?
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
0 = rows and columns independent.
Your data
Edit the counts| Low | Mid | High | Total | |
|---|---|---|---|---|
| Row A | 28E = 22.1 | 20E = 17.8 | 24E = 32.2 | 72 |
| Row B | 18E = 23.9 | 17E = 19.2 | 43E = 34.8 | 78 |
| Total | 46 | 37 | 67 | 150 |
E is the count expected if rows and columns were unrelated.
If H₀ were true
- The reference: how χ² varies across samples when H₀ is true (χ² approximation).
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .023).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- observed count in cell (i, j)
- the count expected if rows and columns were independent
- 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 H₀.
Question and hypotheses
H0: two categorical variables are independent.
Assumptions
Independent sampled units, mutually exclusive categories, multinomial sampling and adequate expected counts.
Formula
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.
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]]))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
- R Pearson chi square testsstat.ethz.ch
- chisq.teststat.ethz.ch
- 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.