PUBH-311 · Lesson 7 of 12 · 24 min

Chi-square tests for tables

▶ Video coming soon A video version of this lesson is on the way.

Planning for the autumn influenza campaign began in June. The immunization program lead in Kestrel Valley wanted to know whether vaccine uptake last season had differed by age group, and, if so, which group to target. The survey showed that 30 percent of adults aged 18 to 39, 40 percent of those aged 40 to 64 and 60 percent of those aged 65 and older had been vaccinated. Jonah was asked to test whether those differences could be due to chance. Two proportions could be compared with the z-test from the last lesson, but here there were three groups. The tool for the job was the chi-square test.

Chi-square tests (chi is the Greek letter χ, pronounced "kye") are the workhorses for categorical data. This lesson covers contingency tables, the chi-square test of independence, the goodness-of-fit test, the conditions for using them, Fisher’s exact test for small samples, and extensions such as tests for trend and stratified analysis. It also shows how chi-square results should be reported alongside effect measures.

Contingency tables

A contingency table (cross-tabulation) displays the joint distribution of two categorical variables, with one variable defining the rows and the other the columns. Each cell holds the count of observations with that combination of categories, and the marginal totals along the edges give the totals for each row and column. A table with \(r\) rows and \(c\) columns is called an \(r \times c\) table. The two-by-two tables of Lesson 6 are the simplest case.

Table 1. Influenza vaccination last season by age group, Kestrel Valley survey (invented data).
Age groupVaccinatedNot vaccinatedTotalProportion vaccinated
18 to 391202804000.30
40 to 641802704500.40
65 and older2101403500.60
Total5106901,2000.425

When presenting a contingency table, decide which percentages answer the question. Here we want to compare vaccination across age groups, so we calculate row percentages: the proportion vaccinated within each age group. Column percentages (the age distribution of vaccinated and unvaccinated people) answer a different question. Always make it clear which way the percentages run.

The chi-square test of independence

The chi-square test of independence asks whether two categorical variables are associated in the population. The null hypothesis is that they are independent: the proportion vaccinated is the same in every age group. The alternative is that the proportions differ somewhere.

The test compares the observed counts \(O\) with the expected counts \(E\) that we would see, on average, if the null hypothesis were true. Under independence, the expected count in any cell is

\[E = \frac{\text{row total} \times \text{column total}}{\text{grand total}}\]

The test statistic adds up, over all cells, the squared difference between observed and expected counts divided by the expected count:

\[\chi^2 = \sum \frac{(O - E)^2}{E}\]

If the null hypothesis is true, the observed counts should be close to the expected ones and \(\chi^2\) small. Large values indicate that the observed pattern departs from independence. Under the null, the statistic follows a chi-square distribution with \((r - 1)(c - 1)\) degrees of freedom. The distribution is right-skewed, takes only positive values, and its shape depends on the degrees of freedom (Figure 1). Only large values count as evidence against the null, so the p-value is always the upper tail area.

Chi-square density curves for 1, 2 and 4 degrees of freedom. The 1 and 2 degree curves decline from the left; the 4 degree curve rises to a peak near 2 then declines. A dashed line marks the critical value 5.99 for 2 degrees of freedom, with the upper tail shaded.
Figure 1. Chi-square distributions. The critical value at α = 0.05 is 3.84 for 1 df, 5.99 for 2 df and 9.49 for 4 df.

Worked problem

Is influenza vaccination associated with age group?

Use the counts in Table 1 to test whether vaccination is independent of age group at α = 0.05.

Show solution
  1. Expected count for 18 to 39, vaccinated: \(400 \times 510 / 1200 = 170\). For not vaccinated: \(400 \times 690 / 1200 = 230\).
  2. For 40 to 64: \(450 \times 510/1200 = 191.25\) and \(450 \times 690/1200 = 258.75\). For 65 and older: \(350 \times 510/1200 = 148.75\) and \(350 \times 690/1200 = 201.25\).
  3. Contributions \((O-E)^2/E\): 18 to 39: \((120-170)^2/170 = 14.71\) and \((280-230)^2/230 = 10.87\). 40 to 64: \((180-191.25)^2/191.25 = 0.66\) and \((270-258.75)^2/258.75 = 0.49\). 65 and older: \((210-148.75)^2/148.75 = 25.22\) and \((140-201.25)^2/201.25 = 18.64\).
  4. Sum: \(\chi^2 = 14.71 + 10.87 + 0.66 + 0.49 + 25.22 + 18.64 = 70.6\).
  5. Degrees of freedom: \((3 - 1)(2 - 1) = 2\). The critical value is 5.99; 70.6 far exceeds it, and p is less than 0.001.

Answer: Vaccination is strongly associated with age group (χ² = 70.6, df = 2, p < 0.001). The largest contributions come from the youngest group (fewer vaccinated than expected) and the oldest group (more than expected).

Looking at the individual cell contributions, or at standardized residuals \((O - E)/\sqrt{E}\), shows where the association lies. Here the middle age group is close to what independence predicts, while the youngest and oldest groups depart in opposite directions. That is more useful to the program lead than the overall p-value, which only says the groups are not all the same.

Why the degrees of freedom are (r − 1)(c − 1)

Once the marginal totals are fixed, only some cells are free to vary. In a 3 × 2 table, if you know the vaccinated counts for two age groups, the third is determined by the column total, and each not-vaccinated count is determined by its row total. Only two cells are free, giving 2 degrees of freedom. In a 2 × 2 table only one cell is free.

Conditions for the chi-square test

The chi-square test relies on an approximation that works well when expected counts are not too small. The usual rule, from the statistician William Cochran, is that no expected count should be below 1 and no more than 20 percent of expected counts should be below 5. For a 2 × 2 table, this effectively means all expected counts should be at least 5. Note that the rule concerns expected counts, not observed ones; an observed zero is fine if its expected count is large enough.

The test also requires that each observation appears in only one cell and that observations are independent. Paired data, such as before-and-after answers from the same people, need McNemar’s test instead. And the cells must contain counts, never percentages or rates; entering percentages gives a meaningless statistic.

When expected counts are too small, there are several options: combine sparse categories if it makes sense (for example, merging two small age groups), or use Fisher’s exact test.

Fisher’s exact test

Fisher’s exact test, devised by Ronald Fisher in the 1930s, calculates the exact probability of obtaining the observed table, or one more extreme, given the marginal totals, using the hypergeometric distribution. It does not rely on a large-sample approximation, so it is valid for small samples. It is most often used for 2 × 2 tables, and software can extend it to larger tables. The calculations are tedious by hand but immediate with software.

Worked problem

A small outbreak at a community supper

After a church supper, 24 attendees were interviewed. Of 9 who ate the potato salad, 7 became ill; of 15 who did not, 3 became ill. Is a chi-square test appropriate, and what does Fisher’s exact test show?

Show solution
  1. Totals: 10 ill and 14 well; 9 ate the salad and 15 did not.
  2. Smallest expected count: ate salad and ill, \(9 \times 10 / 24 = 3.75\). Ate salad and well: \(9 \times 14/24 = 5.25\). One of four expected counts (25 percent) is below 5, so the chi-square approximation is doubtful.
  3. Fisher’s exact test (two-sided), from software: p = 0.010.
  4. Effect measures: attack rates are 7/9 = 0.78 and 3/15 = 0.20; risk ratio = 3.9; odds ratio = (7 × 12)/(2 × 3) = 14.

Answer: Use Fisher’s exact test: the association between eating potato salad and illness is significant (p = 0.010), with attack rates of 78 versus 20 percent. Outbreak investigators would treat the salad as a strong suspect and look for laboratory confirmation.

For 2 × 2 tables with moderate counts, some textbooks recommend Yates’ continuity correction, which subtracts 0.5 from each \(|O - E|\) before squaring. It makes the test more conservative. Many statisticians now prefer either the uncorrected test for adequate samples or Fisher’s exact test for small ones, but you will see the correction in older papers and software output.

The chi-square goodness-of-fit test

The goodness-of-fit test compares the distribution of a single categorical variable with a distribution specified in advance. The expected counts come from the hypothesized proportions, the statistic is calculated in the same way, and the degrees of freedom are the number of categories minus 1.

Worked problem

Are foodborne illness reports evenly spread across the year?

A region recorded 200 confirmed cases of a foodborne infection in a year: 38 in January to March, 45 in April to June, 72 in July to September and 45 in October to December. Test whether cases are equally likely in each quarter.

Show solution
  1. Null hypothesis: each quarter has probability 0.25. Expected count per quarter: \(200 \times 0.25 = 50\).
  2. Contributions: \((38-50)^2/50 = 2.88\); \((45-50)^2/50 = 0.50\); \((72-50)^2/50 = 9.68\); \((45-50)^2/50 = 0.50\).
  3. Sum: \(\chi^2 = 13.56\), with 4 − 1 = 3 degrees of freedom.
  4. The critical value for 3 df is 7.81, so the result is significant; p = 0.004.

Answer: Cases were not evenly distributed (χ² = 13.56, df = 3, p = 0.004); the summer quarter had the most, consistent with the known seasonality of many foodborne infections. Quarters differ slightly in length, a detail a more careful analysis would build into the expected counts.

Goodness-of-fit tests are also used to check whether a sample resembles its population, for example whether the age and sex distribution of survey respondents matches census figures, and to check whether data follow a theoretical distribution such as the Poisson.

The chi-square test and the z-test

For a 2 × 2 table, the chi-square test of independence and the two-sample z-test for proportions are the same test: the chi-square statistic equals the square of the z statistic, and the p-values are identical. For the cessation trial in Lesson 6, \(z = 2.31\) and \(\chi^2 = 5.33\), both with p = 0.021. The z-test has one advantage: it can be one-sided and naturally gives a confidence interval for the difference. The chi-square test generalizes to larger tables.

Beyond the basic test

Ordered categories: the test for trend

The standard chi-square test treats categories as unordered. When one variable is ordinal, such as age group or income level, a more powerful question is whether the proportion rises or falls steadily across the ordered categories. The chi-square test for trend (Cochran-Armitage test) has 1 degree of freedom and directly tests for a linear trend. In Table 1, the proportion vaccinated rises steadily with age, and a trend test would confirm this with a single, focused statistic.

Measuring the strength of association

A chi-square statistic grows with sample size, so it measures the strength of evidence, not the strength of the association. For 2 × 2 tables, the risk difference, risk ratio and odds ratio describe strength. For larger tables, Cramér’s V, which ranges from 0 (no association) to 1 (perfect association), is sometimes reported: \(V = \sqrt{\chi^2 / (n \times (k - 1))}\), where \(k\) is the smaller of the number of rows and columns. For Table 1, \(V = \sqrt{70.6/1200} = 0.24\), a moderate association.

Stratified tables and confounding

An association in a two-way table can be distorted by a third variable. If vaccinated people in the survey are older, and older people have more chronic disease, a crude table of vaccination by chronic disease will reflect age as well. One solution is to split the data into strata (age groups) and analyse a 2 × 2 table within each. The Mantel-Haenszel method combines the stratum-specific odds ratios or risk ratios into a single adjusted estimate and provides a test of association controlling for the stratifying variable. Principles of Epidemiology introduced stratification as a way of controlling confounding; regression models (Lessons 9 and 10) extend the idea to several variables at once.

Stratification also reveals Simpson’s paradox, in which an association in combined data reverses in every stratum. It is a reminder that a single table, however significant, can mislead when an important variable is ignored.

Reporting chi-square results

A good report gives the table (with counts and the relevant percentages), the test statistic, degrees of freedom and p-value, and, crucially, a description of the pattern and an effect measure. For example: "Influenza vaccination increased with age, from 30 percent among adults aged 18 to 39 to 60 percent among those 65 and older (χ² = 70.6, df = 2, p < 0.001)." That sentence tells the reader what is happening, not just that something is.

Back to the campaign

The program lead used the analysis to set targets. Because uptake among adults aged 18 to 39 was half that of older adults, and the largest chi-square contributions came from that group, the campaign added evening workplace clinics and pharmacy promotions for younger adults. Jonah noted in his report that the survey could not say why younger adults were less often vaccinated; that would need a different study.

Common mistakes

  • MistakeEntering percentages instead of counts into a chi-square test.

    InsteadChi-square tests require the actual counts in each cell.

  • MistakeChecking the minimum observed count instead of expected counts.

    InsteadThe conditions concern expected counts; use Fisher’s exact test if too many are small.

  • MistakeReporting only "p < 0.001" for a table.

    InsteadDescribe the pattern with percentages and an effect measure, and say where the association lies.

  • MistakeUsing the chi-square statistic as a measure of strength of association.

    Insteadχ² grows with sample size; use RR, OR, risk difference or Cramér’s V for strength.

  • MistakeIgnoring the order of ordinal categories.

    InsteadConsider a test for trend, which is more powerful for ordered categories.

Summary and key terms

  • Contingency tables cross-tabulate two categorical variables; choose row or column percentages to answer the question.
  • The chi-square test of independence compares observed and expected counts, with expected = row total × column total / grand total.
  • The statistic Σ(O − E)²/E has (r − 1)(c − 1) degrees of freedom; only large values are evidence against independence.
  • Expected counts should mostly be 5 or more; otherwise combine categories or use Fisher’s exact test.
  • The goodness-of-fit test compares one variable’s distribution with a specified distribution, with categories − 1 df.
  • For 2 × 2 tables, χ² equals z² from the two-proportion test.
  • Tests for trend, Cramér’s V and Mantel-Haenszel stratified analysis extend the basic test.
Contingency table
A table of counts cross-classifying observations by two categorical variables.
Expected count
The count expected in a cell if the null hypothesis of independence were true.
Chi-square test of independence
A test of whether two categorical variables are associated.
Goodness-of-fit test
A chi-square test comparing observed category counts with those expected under a specified distribution.
Fisher’s exact test
An exact test for association in small contingency tables.
Standardized residual
(O − E)/√E for a cell; shows which cells depart most from independence.
Test for trend
A 1-df test of whether a proportion changes steadily across ordered categories.
Mantel-Haenszel method
A method for combining stratum-specific 2 × 2 tables into an adjusted estimate and test.
Cramér’s V
A measure of the strength of association in a contingency table, from 0 to 1.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. In a 2 × 2 table, row totals are 60 and 40, column totals are 30 and 70, and n = 100. Find the expected count in the top-left cell.

    Show answer

    E = 60 × 30/100 = 18.

  2. How many degrees of freedom does a chi-square test of independence have for a 4 × 3 table?

    Show answer

    (4 − 1)(3 − 1) = 6.

  3. A survey has 120 respondents: 70 women and 50 men. The population is half women. Carry out a goodness-of-fit test.

    Show answer

    Expected 60 and 60. χ² = (70 − 60)²/60 + (50 − 60)²/60 = 1.67 + 1.67 = 3.33, df = 1. Below 3.84, so not significant at 0.05 (p ≈ 0.07).

  4. A 2 × 2 table of a rare adverse event has expected counts of 2.1, 3.4, 47.9 and 76.6. Which test should you use?

    Show answer

    Fisher’s exact test, because two of the four expected counts are below 5.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz