# Pearson's chi-squared test

Pearson's chi-squared test or Pearson's $\chi ^{2}$ test is a statistical test applied to sets of categorical data to evaluate how likely it is that any observed difference between the sets arose by chance. It is the most widely used of many chi-squared tests (e.g., Yates, likelihood ratio, portmanteau test in time series, etc.) – statistical procedures whose results are evaluated by reference to the chi-squared distribution. Its properties were first investigated by Karl Pearson in 1900. In contexts where it is important to improve a distinction between the test statistic and its distribution, names similar to Pearson χ-squared test or statistic are used.
It is a p-value test. The setup is as follows:
* Before the experiment, the experimenter fixes a certain number $N$ of samples to take.
* The observed data is $(O_{1},O_{2},...,O_{n})$, the count number of samples from a finite set of given categories. They satisfy $\sum _{i}O_{i}=N$.
* The null hypothesis is that the count numbers are sampled from a multinomial distribution $\mathrm {Multinomial} (N;p_{1},...,p_{n})$. That is, the underlying data is sampled IID from a categorical distribution $\mathrm {Categorical} (p_{1},...,p_{n})$ over the given categories.
* The Pearson's chi-squared test statistic is defined as $\chi ^{2}:=\sum _{i}{\frac {(O_{i}-Np_{i})^{2}}{Np_{i}}}$. The p-value of the test statistic is computed either numerically or by looking it up in a table.
* If the p-value is small enough (usually p < 0.05 by convention), then the null hypothesis is rejected, and we conclude that the observed data does not follow the multinomial distribution.
A simple example is testing the hypothesis that an ordinary six-sided die is "fair" (i. e., all six outcomes are equally likely to occur). In this case, the observed data is $(O_{1},O_{2},...,O_{6})$, the number of times that the dice has fallen on each number. The null hypothesis is $\mathrm {Multinomial} (N;1/6,...,1/6)$, and $\chi ^{2}:=\sum _{i=1}^{6}{\frac {(O_{i}-N/6)^{2}}{N/6}}$. As detailed below, if $\chi ^{2}>11.07$, then the fairness of dice can be rejected at the level of $p<0.05$.

## Usage

Pearson's chi-squared test is used to assess three types of comparison: goodness of fit, homogeneity, and independence.
* A test of goodness of fit establishes whether an observed frequency distribution differs from a theoretical distribution.
* A test of homogeneity compares the distribution of counts for two or more groups using the same categorical variable (e.g. choice of activity—college, military, employment, travel—of graduates of a high school reported a year after graduation, sorted by graduation year, to see if number of graduates choosing a given activity has changed from class to class, or from decade to decade).
* A test of independence assesses whether observations consisting of measures on two variables, expressed in a contingency table, are independent of each other (e.g. polling responses from people of different nationalities to see if one's nationality is related to the response).
For all three tests, the computational procedure includes the following steps:
* Calculate the chi-squared test statistic, $\chi ^{2}$, which resembles a normalized sum of squared deviations between observed and theoretical frequencies (see below).
* Determine the degrees of freedom, df, of that statistic.
** For a test of goodness-of-fit, df = Cats − Params, where Cats is the number of observation categories recognized by the model, and Params is the number of parameters in the model adjusted to make the model best fit the observations: The number of categories reduced by the number of fitted parameters in the distribution.
** For a test of homogeneity, df = (Rows − 1)×(Cols − 1), where Rows corresponds to the number of categories (i.e. rows in the associated contingency table), and Cols corresponds to the number of independent groups (i.e. columns in the associated contingency table).
** For a test of independence, df = (Rows − 1)×(Cols − 1), where in this case, Rows corresponds to the number of categories in one variable, and Cols corresponds to the number of categories in the second variable.
* Select a desired level of confidence (significance level, p-value, or the corresponding alpha level) for the result of the test.
* Compare $\chi ^{2}$ to the critical value from the chi-squared distribution with df degrees of freedom and the selected confidence level (one-sided, since the test is only in one direction, i.e. is the test value greater than the critical value?), which in many cases gives a good approximation of the distribution of $\chi ^{2}$.
* Sustain or reject the null hypothesis that the observed frequency distribution is the same as the theoretical distribution based on whether the test statistic exceeds the critical value of $\chi ^{2}$. If the test statistic exceeds the critical value of $\chi ^{2}$, the null hypothesis ($H_{0}$ = there is no difference between the distributions) can be rejected, and the alternative hypothesis ($H_{1}$ = there is a difference between the distributions) can be accepted, both with the selected level of confidence. If the test statistic falls below the threshold $\chi ^{2}$ value, then no clear conclusion can be reached, and the null hypothesis is sustained (we fail to reject the null hypothesis), though not necessarily accepted.

## Test for fit of a distribution
### Discrete uniform distribution

In this case $N$ observations are divided among $n$ cells. A simple application is to test the hypothesis that, in the general population, values would occur in each cell with equal frequency. The "theoretical frequency" for any cell (under the null hypothesis of a discrete uniform distribution) is thus calculated as $E_{i}={\frac {N}{n}}\,,$ and the reduction in the degrees of freedom is $p=1$, notionally because the observed frequencies $O_{i}$ are constrained to sum to $N$.
One specific example of its application would be its application for log-rank test.

### Other distributions

When testing whether observations are random variables whose distribution belongs to a given family of distributions, the "theoretical frequencies" are calculated using a distribution from that family fitted in some standard way. The reduction in the degrees of freedom is calculated as $p=s+1$, where $s$ is the number of parameters used in fitting the distribution. For instance, when checking a three-parameter Generalized gamma distribution, $p=4$, and when checking a normal distribution (where the parameters are mean and standard deviation), $p=3$, and when checking a Poisson distribution (where the parameter is the expected value), $p=2$. Thus, there will be $n-p$ degrees of freedom, where $n$ is the number of categories.
The degrees of freedom are not based on the number of observations as with a Student's t or F-distribution. For example, if testing for a fair, six-sided die, there would be five degrees of freedom because there are six categories or parameters (each number); the number of times the die is rolled does not influence the number of degrees of freedom.

### Calculating the test-statistic

The value of the test-statistic is
$\chi ^{2}=\sum _{i=1}^{n}{\frac {(O_{i}-E_{i})^{2}}{E_{i}}}=N\sum _{i=1}^{n}{\frac {\left(O_{i}/N-p_{i}\right)^{2}}{p_{i}}}$
where
* $\chi ^{2}$ = Pearson's cumulative test statistic, which asymptotically approaches a $\chi ^{2}$ distribution.
* $O_{i}$ = the number of observations of type i.
* $N$ = total number of observations
* $E_{i}=Np_{i}$ = the expected (theoretical) count of type i, asserted by the null hypothesis that the fraction of type i in the population is $p_{i}$
* $n$ = the number of cells in the table.
The chi-squared statistic can then be used to calculate a p-value by comparing the value of the statistic to a chi-squared distribution. The number of degrees of freedom is equal to the number of cells $n$, minus the reduction in degrees of freedom, $p$.
The chi-squared statistic can be also calculated as
$\chi ^{2}=\sum _{i=1}^{n}{\frac {O_{i}^{2}}{E_{i}}}-N.$
This result is the consequence of the Binomial theorem.
The result about the numbers of degrees of freedom is valid when the original data are multinomial and hence the estimated parameters are efficient for minimizing the chi-squared statistic. More generally however, when maximum likelihood estimation does not coincide with minimum chi-squared estimation, the distribution will lie somewhere between a chi-squared distribution with $n-1-p$ and $n-1$ degrees of freedom (See for instance Chernoff and Lehmann, 1954).
The chi-squared test indicates a statistically significant association between the level of education completed and routine check-up attendance (chi2(3) = 14.6090, p = 0.002). The proportions suggest that as the level of education increases, so does the proportion of individuals attending routine check-ups. Specifically, individuals who have graduated from college or university attend routine check-ups at a higher proportion (31.52%) compared to those who have not graduated high school (8.44%). This finding may suggest that higher educational attainment is associated with a greater likelihood of engaging in health-promoting behaviors such as routine check-ups.

### Bayesian method

In Bayesian statistics, one would instead use a Dirichlet distribution as conjugate prior. If one took a uniform prior, then the maximum likelihood estimate for the population probability is the observed probability, and one may compute a credible region around this or another estimate.

## Testing for statistical independence

In this case, an "observation" consists of the values of two outcomes and the null hypothesis is that the occurrence of these outcomes is statistically independent. Each observation is allocated to one cell of a two-dimensional array of cells (called a contingency table) according to the values of the two outcomes. If there are r rows and c columns in the table, the "theoretical frequency" for a cell, given the hypothesis of independence, is
$E_{i,j}=Np_{i\cdot }p_{\cdot j},$
where $N$ is the total sample size (the sum of all cells in the table), and
$p_{i\cdot }={\frac {O_{i\cdot }}{N}}=\sum _{j=1}^{c}{\frac {O_{i,j}}{N}},$
is the fraction of observations of type i ignoring the column attribute (fraction of row totals), and $p_{\cdot j}={\frac {O_{\cdot j}}{N}}=\sum _{i=1}^{r}{\frac {O_{i,j}}{N}}$
is the fraction of observations of type j ignoring the row attribute (fraction of column totals). The term "frequencies" refers to absolute numbers rather than already normalized values.
The value of the test-statistic is
$\chi ^{2}=\sum _{i=1}^{r}\sum _{j=1}^{c}{(O_{i,j}-E_{i,j})^{2} \over E_{i,j}}$ $\ \ \ \ =N\sum _{i,j}p_{i\cdot }p_{\cdot j}\left({\frac {(O_{i,j}/N)-p_{i\cdot }p_{\cdot j}}{p_{i\cdot }p_{\cdot j}}}\right)^{2}$
Note that $\chi ^{2}$ is 0 if and only if $O_{i,j}=E_{i,j}\forall i,j$, i.e. only if the expected and true number of observations are equal in all cells.
Fitting the model of "independence" reduces the number of degrees of freedom by p = r + c − 1. The number of degrees of freedom is equal to the number of cells rc, minus the reduction in degrees of freedom, p, which reduces to (r − 1)(c − 1).
For the test of independence, also known as the test of homogeneity, a chi-squared probability of less than or equal to 0.05 (or the chi-squared statistic being at or larger than the 0.05 critical point) is commonly interpreted by applied workers as justification for rejecting the null hypothesis that the row variable is independent of the column variable. The alternative hypothesis corresponds to the variables having an association or relationship where the structure of this relationship is not specified.

## Assumptions

The chi-squared test, when used with the standard approximation that a chi-squared distribution is applicable, has the following assumptions:

### Simple random sample

    The sample data is a random sampling from a fixed distribution or population where every collection of members of the population of the given sample size has an equal probability of selection. Variants of the test have been developed for complex samples, such as where the data is weighted. Other forms can be used such as purposive sampling.

### Sample size (whole table)

    A sample with a sufficiently large size is assumed. If a chi squared test is conducted on a sample with a smaller size, then the chi squared test will yield an inaccurate inference. The researcher, by using chi squared test on small samples, might end up committing a Type II error. For small sample sizes the Cash test is preferred.

### Expected cell count

    Adequate expected cell counts. Some require 5 or more, and others require 10 or more. A common rule is 5 or more in all cells of a 2-by-2 table, and 5 or more in 80% of cells in larger tables, but no cells with zero expected count. When this assumption is not met, Yates's correction is applied.

### Independence

    The observations are always assumed to be independent of each other. This means chi-squared cannot be used to test correlated data (like matched pairs or panel data). In those cases, McNemar's test may be more appropriate.
A test that relies on different assumptions is Fisher's exact test; if its assumption of fixed marginal distributions is met it is substantially more accurate in obtaining a significance level, especially with few observations. In the vast majority of applications this assumption will not be met, and Fisher's exact test will be over conservative and not have correct coverage.

## Derivation

The null distribution of the Pearson statistic with j rows and k columns is approximated by the chi-squared distribution with (k − 1)(j − 1) degrees of freedom.
This approximation arises as the true distribution, under the null hypothesis, if the expected value is given by a multinomial distribution. For large sample sizes, the central limit theorem says this distribution tends toward a certain multivariate normal distribution.

### Two cells

In the special case where there are only two cells in the table, the expected values follow a binomial distribution,
$O\ \sim \ {\mbox{Bin}}(n,p),\,$
where
* p = probability, under the null hypothesis,
* n = number of observations in the sample.
In the above example the hypothesised probability of a male observation is 0.5, with 100 samples. Thus we expect to observe 50 males.
If n is sufficiently large, the above binomial distribution may be approximated by a Gaussian (normal) distribution and thus the Pearson test statistic approximates a chi-squared distribution,
${\text{Bin}}(n,p)\approx {\text{N}}(np,np(1-p)).\,$
Let O$_1$ be the number of observations from the sample that are in the first cell. The Pearson test statistic can be expressed as
${\frac {(O_{1}-np)^{2}}{np}}+{\frac {(n-O_{1}-n(1-p))^{2}}{n(1-p)}},$
which can in turn be expressed as
$\left({\frac {O_{1}-np}{\sqrt {np(1-p)}}}\right)^{2}.$
By the normal approximation to a binomial this is the squared of one standard normal variate, and hence is distributed as chi-squared with 1 degree of freedom. Note that the denominator is one standard deviation of the Gaussian approximation, so can be written
${\frac {(O_{1}-\mu )^{2}}{\sigma ^{2}}}.$
So as consistent with the meaning of the chi-squared distribution, we are measuring how probable the observed number of standard deviations away from the mean is under the Gaussian approximation (which is a good approximation for large n).
The chi-squared distribution is then integrated on the right of the statistic value to obtain the P-value, which is equal to the probability of getting a statistic equal or bigger than the observed one, assuming the null hypothesis.

### Two-by-two contingency tables

When the test is applied to a contingency table containing two rows and two columns, the test is equivalent to a Z-test of proportions.

### Many cells

Broadly similar arguments as above lead to the desired result, though the details are more involved. One may apply an orthogonal change of variables to turn the limiting summands in the test statistic into one fewer squares of i.i.d. standard normal random variables.
Let us now prove that the distribution indeed approaches asymptotically the $\chi ^{2}$ distribution as the number of observations approaches infinity.
Let $n$ be the number of observations, $m$ the number of cells and $p_{i}$ the probability of an observation to fall in the i-th cell, for $1\leq i\leq m$. We denote by $\{k_{i}\}$ the configuration where for each i there are $k_{i}$ observations in the i-th cell. Note that
$\sum _{i=1}^{m}k_{i}=n\qquad {\text{and}}\qquad \sum _{i=1}^{m}p_{i}=1.$
Let $\chi _{P}^{2}(\{k_{i}\},\{p_{i}\})$ be Pearson's cumulative test statistic for such a configuration, and let $\chi _{P}^{2}(\{p_{i}\})$ be the distribution of this statistic. We will show that the latter probability approaches the $\chi ^{2}$ distribution with $m-1$ degrees of freedom, as $n\to \infty .$
For any arbitrary value T:
$P(\chi _{P}^{2}(\{p_{i}\})>T)=\sum _{\{k_{i}\}|\chi _{P}^{2}(\{k_{i}\},\{p_{i}\})>T}{\frac {n!}{k_{1}!\cdots k_{m}!}}\prod _{i=1}^{m}{p_{i}}^{k_{i}}$
We will use a procedure similar to the approximation in de Moivre–Laplace theorem. Contributions from small $k_{i}$ are of subleading order in $n$ and thus for large $n$ we may use Stirling's formula for both $n!$ and $k_{i}!$ to get the following:
$P(\chi _{P}^{2}(\{p_{i}\})>T)\sim \sum _{\{k_{i}\}|\chi _{P}^{2}(\{k_{i}\},\{p_{i}\})>T}\prod _{i=1}^{m}\left({\frac {np_{i}}{k_{i}}}\right)^{k_{i}}{\sqrt {\frac {2\pi n}{\prod _{i=1}^{m}2\pi k_{i}}}}$
By substituting for
$x_{i}={\frac {k_{i}-np_{i}}{\sqrt {n}}},\qquad i=1,\cdots ,m-1,$
we may approximate for large $n$ the sum over the $k_{i}$ by an integral over the $x_{i}$. Noting that:
$k_{m}=np_{m}-{\sqrt {n}}\sum _{i=1}^{m-1}x_{i},$
we arrive at
${\begin{aligned}P(\chi _{P}^{2}(\{p_{i}\})>T)&\sim {\sqrt {\frac {2\pi n}{\prod _{i=1}^{m}2\pi k_{i}}}}\int _{\chi _{P}^{2}(\{{\sqrt {n}}x_{i}+np_{i}\},\{p_{i}\})>T}\left\{\prod _{i=1}^{m-1}{{\sqrt {n}}dx_{i}}\right\}\left\{\prod _{i=1}^{m-1}\left(1+{\frac {x_{i}}{{\sqrt {n}}p_{i}}}\right)^{-(np_{i}+{\sqrt {n}}x_{i})}\left(1-{\frac {\sum _{i=1}^{m-1}{x_{i}}}{{\sqrt {n}}p_{m}}}\right)^{-\left(np_{m}-{\sqrt {n}}\sum _{i=1}^{m-1}x_{i}\right)}\right\}\\&={\sqrt {\frac {2\pi n}{\prod _{i=1}^{m}\left(2\pi np_{i}+2\pi {\sqrt {n}}x_{i}\right)}}}\int _{\chi _{P}^{2}(\{{\sqrt {n}}x_{i}+np_{i}\},\{p_{i}\})>T}\left\{\prod _{i=1}^{m-1}{{\sqrt {n}}dx_{i}}\right\}\times \\&\qquad \qquad \times \left\{\prod _{i=1}^{m-1}\exp \left[-\left(np_{i}+{\sqrt {n}}x_{i}\right)\ln \left(1+{\frac {x_{i}}{{\sqrt {n}}p_{i}}}\right)\right]\exp \left[-\left(np_{m}-{\sqrt {n}}\sum _{i=1}^{m-1}x_{i}\right)\ln \left(1-{\frac {\sum _{i=1}^{m-1}{x_{i}}}{{\sqrt {n}}p_{m}}}\right)\right]\right\}\end{aligned}}$
By expanding the logarithm and taking the leading terms in $n$, we get
$P(\chi _{P}^{2}(\{p_{i}\})>T)\sim {\frac {1}{\sqrt {(2\pi )^{m-1}\prod _{i=1}^{m}p_{i}}}}\int _{\chi _{P}^{2}(\{{\sqrt {n}}x_{i}+np_{i}\},\{p_{i}\})>T}\left\{\prod _{i=1}^{m-1}dx_{i}\right\}\prod _{i=1}^{m-1}\exp \left[-{\frac {1}{2}}\sum _{i=1}^{m-1}{\frac {x_{i}^{2}}{p_{i}}}-{\frac {1}{2p_{m}}}\left(\sum _{i=1}^{m-1}{x_{i}}\right)^{2}\right]$
Pearson's chi, $\chi _{P}^{2}(\{k_{i}\},\{p_{i}\})=\chi _{P}^{2}(\{{\sqrt {n}}x_{i}+np_{i}\},\{p_{i}\})$, is precisely the argument of the exponent (except for the −1/2; note that the final term in the exponent's argument is equal to $(k_{m}-np_{m})^{2}/(np_{m})$).
This argument can be written as:
$-{\frac {1}{2}}\sum _{i,j=1}^{m-1}x_{i}A_{ij}x_{j},\qquad i,j=1,\cdots ,m-1,\quad A_{ij}={\tfrac {\delta _{ij}}{p_{i}}}+{\tfrac {1}{p_{m}}}.$
$A$ is a regular symmetric $(m-1)\times (m-1)$ matrix, and hence diagonalizable. It is therefore possible to make a linear change of variables in $\{x_{i}\}$ so as to get $m-1$ new variables $\{y_{i}\}$ so that:
$\sum _{i,j=1}^{m-1}x_{i}A_{ij}x_{j}=\sum _{i=1}^{m-1}y_{i}^{2}.$
This linear change of variables merely multiplies the integral by a constant Jacobian, so we get:
$P(\chi _{P}^{2}(\{p_{i}\})>T)\sim C\int _{\sum _{i=1}^{m-1}y_{i}^{2}>T}\left\{\prod _{i=1}^{m-1}dy_{i}\right\}\prod _{i=1}^{m-1}\exp \left[-{\frac {1}{2}}\left(\sum _{i=1}^{m-1}y_{i}^{2}\right)\right]$
Where C is a constant.
This is the probability that squared sum of $m-1$ independent normally distributed variables of zero mean and unit variance will be greater than T, namely that $\chi ^{2}$ with $m-1$ degrees of freedom is larger than T.
We have thus shown that at the limit where $n\to \infty ,$ the distribution of Pearson's chi approaches the chi distribution with $m-1$ degrees of freedom.
An alternative derivation is on the multinomial distribution page.

## Examples
### Fairness of dice

A 6-sided die is thrown 60 times. The number of times it lands with 1, 2, 3, 4, 5 and 6 face up is 5, 8, 9, 8, 10 and 20, respectively. Is the die biased, according to the Pearson's chi-squared test at a significance level of 95% and/or 99%?
The null hypothesis is that the die is unbiased, hence each number is expected to occur the same number of times, in this case, ⁠60/n⁠ = 10. The outcomes can be tabulated as follows:
| $i$ | $O_{i}$ | $E_{i}$ | $O_{i}-E_{i}$ | $(O_{i}-E_{i})^{2}$ |
| 1 | 5 | 10 | −5 | 25 |
| 2 | 8 | 10 | −2 | 4 |
| 3 | 9 | 10 | −1 | 1 |
| 4 | 8 | 10 | −2 | 4 |
| 5 | 10 | 10 | 0 | 0 |
| 6 | 20 | 10 | 10 | 100 |
| Sum | Sum | Sum | Sum | 134 |
We then consult an Upper-tail critical values of chi-square distribution table, the tabular value refers to the sum of the squared variables each divided by the expected outcomes. For the present example, this means
${\chi ^{2}}=25/10+4/10+1/10+4/10+0/10+100/10=13.4$
This is the experimental result whose unlikeliness (with a fair die) we wish to estimate.
| Degrees of freedom | Probability less than the critical value | Probability less than the critical value | Probability less than the critical value | Probability less than the critical value | Probability less than the critical value |
| Degrees of freedom | 0.90 | 0.95 | 0.975 | 0.99 | 0.999 |
| 5 | 9.236 | 11.070 | 12.833 | 15.086 | 20.515 |
The experimental sum of 13.4 is between the critical values of 97.5% and 99% significance or confidence (p-value). Specifically, getting 20 rolls of 6, when the expectation is only 10 such values, is unlikely with a fair die.

### Chi-squared goodness of fit test

In this context, the frequencies of both theoretical and empirical distributions are unnormalised counts, and for a chi-squared test the total sample sizes $N$ of both these distributions (sums of all cells of the corresponding contingency tables) have to be the same.
For example, to test the hypothesis that a random sample of 100 people has been drawn from a population in which men and women are equal in frequency, the observed number of men and women would be compared to the theoretical frequencies of 50 men and 50 women. If there were 44 men in the sample and 56 women, then
$\chi ^{2}={(44-50)^{2} \over 50}+{(56-50)^{2} \over 50}=1.44.$
If the null hypothesis is true (i.e., men and women are chosen with equal probability), the test statistic will be drawn from a chi-squared distribution with one degree of freedom (because if the male frequency is known, then the female frequency is determined).
Consultation of the chi-squared distribution for 1 degree of freedom shows that the probability of observing this difference (or a more extreme difference than this) if men and women are equally numerous in the population is approximately 0.23. This probability is higher than conventional criteria for statistical significance (0.01 or 0.05), so normally we would not reject the null hypothesis that the number of men in the population is the same as the number of women (i.e., we would consider our sample within the range of what we would expect for a 50/50 male–female ratio.)

## Problems

The approximation to the chi-squared distribution breaks down if expected frequencies are too low. It will normally be acceptable so long as no more than 20% of the events have expected frequencies below 5. Where there is only 1 degree of freedom, the approximation is not reliable if expected frequencies are below 10. In this case, a better approximation can be obtained by reducing the absolute value of each difference between observed and expected frequencies by 0.5 before squaring; this is called Yates's correction for continuity.
In cases where the expected value, E, is found to be small (indicating a small underlying population probability, and/or a small number of observations), the normal approximation of the multinomial distribution can fail, and in such cases it is found to be more appropriate to use the G-test, a likelihood ratio-based test statistic. When the total sample size is small, it is necessary to use an appropriate exact test, typically either the binomial test or, for contingency tables, Fisher's exact test. This test uses the conditional distribution of the test statistic given the marginal totals, and thus assumes that the margins were determined before the study; alternatives such as Boschloo's test which do not make this assumption are uniformly more powerful.
It can be shown that the $\chi ^{2}$ test is a low order approximation of the $\Psi$ test. The above reasons for the above issues become apparent when the higher order terms are investigated.