A contingency table counts people in the cells of two categorical variables. The chi-square test asks if the two variables are associated. Karl Pearson published the test in 1900. Fisher corrected its degrees of freedom in 1922 (Chapter 1). Chapter 3 showed that prop.test() reports \(Z^2\) as a chi-square statistic. For a 2 × 2 table, Pearson’s statistic is the square of the two-proportion z statistic.
8.1 The problem
Breast cancer is more common in women of high socioeconomic status. These women also have their first child at a later age. One hypothesis says that the interval between menarche and the first birth increases the risk of breast cancer. If the hypothesis is true, a late first birth is a risk factor.
MacMahon and colleagues did a case-control study in hospitals in 7 areas of the world (Bulletin of the WHO, 1970). The areas included Boston, South Wales, Athens and Tokyo. The cases were women with breast cancer. The controls were women of similar age in the same hospitals at the same time, without breast cancer. We use the women with at least one birth, as given in Rosner, Fundamentals of Biostatistics.
n_case <-3220; x_case <-683# cases with first birth at age 30 or moren_ctrl <-10245; x_ctrl <-1498# controls with first birth at age 30 or moretab <-matrix(c(x_case, n_case - x_case, x_ctrl, n_ctrl - x_ctrl), nrow =2, byrow =TRUE,dimnames =list(status =c("case", "control"), first_birth =c(">= 30", "<= 29")))tab
first_birth
status >= 30 <= 29
case 683 2537
control 1498 8747
Of the 3,220 cases, 21.2% had their first birth at age 30 or more. Of the 10,245 controls, 14.6% did. The gap is 0.066.
Is a first birth at age 30 or more associated with breast cancer?
8.2 Intuitive solution
Suppose that age at first birth has no relation to breast cancer. Then the labels “case” and “control” are arbitrary. Any 3,220 of the 13,465 women can carry the label “case”. We can shuffle the labels, calculate the gap again, and repeat this 10,000 times. The animated Wilcoxon rank-sum test of the course uses the same idea for ranks (Chapter 6).
set.seed(1900)late <-rep(c(1, 0), c(x_case + x_ctrl, N - x_case - x_ctrl)) # 1 = first birth at 30 or moreis_case <-rep(c(TRUE, FALSE), c(n_case, n_ctrl))shuffled <-replicate(10000, { s <-sample(is_case) # shuffle the case and control labelsmean(late[s]) -mean(late[!s])})c(largest_shuffled_gap =max(abs(shuffled)), observed_gap = gap)
Figure 8.1: The gap in the proportion with a first birth at 30 or more (cases minus controls) after 10,000 random shuffles of the case and control labels. The red curve is the normal approximation. The vertical line is the observed gap, far beyond all the shuffles.
The largest shuffled gap is 0.032. The observed gap of 0.066 is 2.1 times larger. None of the 10,000 shuffles comes close, so the permutation p-value is less than 1/10,000. The shuffled gaps follow the red normal curve, and the formal test uses this curve.
8.3 Formal solution
8.3.1 Two proportions and the z-test
Let \(p_1\) be the probability of a first birth at 30 or more in cases, and \(p_2\) in controls. The null hypothesis is \(H_0: p_1 = p_2 = p\). Under \(H_0\), both groups share one proportion. We estimate it from the two groups together:
\[
\hat p = \frac{x_1 + x_2}{n_1 + n_2}, \qquad
z = \frac{\hat p_1 - \hat p_2}{\sqrt{\hat p (1 - \hat p)\,(1/n_1 + 1/n_2)}}.
\]
By the central limit theorem, \(z\) follows a standard normal distribution under \(H_0\). The approximation is good when \(n \hat p (1 - \hat p) \ge 5\) in each group.
z <- gap / se0c(pooled_p = p_pool, se = se0, z = z, p_value =2*pnorm(-abs(z)))
pooled_p se z p_value
1.619755e-01 7.443416e-03 8.852674e+00 8.544684e-19
The pooled proportion is 0.162 and the standard error is 0.0074. The gap of 0.066 is 8.85 standard errors. The two-sided p-value is 8.54e-19. This standard error is the SD of the red curve in Figure 8.1.
8.3.2 Observed and expected counts
Pearson’s form of the test uses counts in place of proportions. If \(H_0\) is true, each row has the pooled proportion \(\hat p\) in the first column. The expected count of cases with a late first birth is \(n_1 \hat p\). In general, the expected count in a cell is
All four cells have the same gap \(|O - E|\) of 161.4. The margins are fixed, so the other three cells follow from one cell. The division by \(E\) makes each gap relative to its cell. A gap of 161 in a cell that expects 522 contributes 49.97. The same gap in a cell that expects 8,586 contributes 3.04.
The total is \(X^2 =\) 78.37. This is \(z^2 =\) 8.85\(^2\). For a 2 × 2 table, the chi-square test and the two-proportion z-test are the same test.
8.3.3 Degrees of freedom
Under \(H_0\), each \((O - E)/\sqrt{E}\) is close to a standard normal. A sum of \(k\) independent squared standard normals has a chi-square distribution with \(k\) degrees of freedom (df). The cells are not independent, because the row and column totals are fixed. In a table with \(R\) rows and \(C\) columns, only \((R - 1)(C - 1)\) cells are free, and the margins give the others. Fisher showed this in 1922 (Chapter 1). A 2 × 2 table has \((2 - 1)(2 - 1) = 1\) df.
The shuffles of Figure 8.1 show this result. We divide each shuffled gap by the standard error and square it. Figure 8.2 shows that the squares follow the chi-square distribution with 1 df.
Figure 8.2: The squared z statistic after each of the 10,000 shuffles of the case and control labels. The red curve is the chi-square distribution with 1 df.
X-squared: 78.37, the sum that we calculated by hand.
df: 1, from \((R - 1)(C - 1)\).
p-value: the area of the chi-square curve with 1 df above 78.37. R prints < 2.2e-16, the smallest value that it shows.
By default, chisq.test() applies the Yates continuity correction to a 2 × 2 table. The correction subtracts 0.5 from each \(|O - E|\) before it squares the gap.
With these large counts, the correction changes \(X^2\) from 78.37 to 77.89. For small counts the difference is larger.
The chi-square approximation needs large expected counts. For a 2 × 2 table, all four expected counts must be 5 or more. For a larger table, use the test only if no more than 1/5 of the cells have \(E < 5\) and no cell has \(E < 1\) (Cochran 1954, Chapter 1). Here the smallest expected count is 521.6.
8.3.5 More than two columns
Age at first birth has more than two categories. Rosner gives the full 2 × 5 table.
The same formula for \(E\) and \(X^2\) applies to all 10 cells. The df are \((2 - 1)(5 - 1) =\) 4. \(X^2\) is 130.3, and the smallest expected count is 150. The test rejects \(H_0\), but it says only that the proportion of cases differs between the columns. Figure 8.3 shows the direction.
Figure 8.3: Percentage of cases in each group of age at first birth (MacMahon et al. 1970, from Rosner). The bars are 95% confidence intervals. The percentage increases with age at first birth.
Chi-squared Test for Trend in Proportions
data: age_df$cases out of age_df$total ,
using scores: 1 2 3 4 5
X-squared = 129.01, df = 1, p-value < 2.2e-16
The columns have an order. A test for trend asks if the proportion of cases increases in a straight line across the columns. The test has 1 df, and here \(X^2 =\) 129. This is almost all of the 130.3 of the general test. The general test spreads its 4 df over all patterns of the five percentages. The trend test uses its 1 df for the increase that the hypothesis predicts.
8.4 Goodness of fit
In 1900, Pearson made the test to check if a probability model fits observed counts. Bortkiewicz counted the soldiers that horse kicks killed in 10 corps of the Prussian army, 1875 to 1894 (Chapter 1). This gives 200 corps-years. Rare, independent events at a constant rate follow a Poisson distribution.
# A tibble: 3 × 3
group O E
<chr> <int> <dbl>
1 0 109 109.
2 1 65 66.3
3 2 or more 26 25.0
X2_gof <-sum((merged$O - merged$E)^2/ merged$E)df_gof <-nrow(merged) -1-1# groups - total - lambdap_gof <-pchisq(X2_gof, df_gof, lower.tail =FALSE)c(X2 = X2_gof, df = df_gof, p = p_gof)
X2 df p
0.06278383 1.00000000 0.80214888
The mean is \(\hat\lambda =\) 0.61 deaths per corps-year. The expected counts for 3 and 4 deaths are below 5. Together they expect only 4.74 corps-years, so we merge 2, 3 and 4 deaths into “2 or more”. The df are the 3 groups minus 1 for the fixed total, minus 1 for the estimate of \(\lambda\). \(X^2\) is 0.06 on 1 df, with p = 0.8. The Poisson model fits the data.
The function chisq.test(O, p = E / sum(E)) gives the same \(X^2\) with 2 df. The function treats \(\lambda\) as known, and we estimated \(\lambda\) from the same data. Its p-value of 0.97 is too large. Each parameter that you estimate from the data removes 1 df. Calculate the p-value with pchisq() and the correct df.
8.5 Summary
The chi-square test compares observed counts with the counts that we expect if the row and column variables are independent.
Pearson’s statistic \(X^2 = \sum (O - E)^2 / E\) has \((R - 1)(C - 1)\) df. For a 2 × 2 table, it is the square of the two-proportion z statistic.
The chi-square approximation needs expected counts of 5 or more in most cells.
A goodness-of-fit test loses 1 df for each parameter that you estimate from the data.