Statistics tutorial · Chapter 06
Contingency tables
A contingency table crosses two categorical variables: each cell contains a number of subjects (or events). In Variance, rows are the groups (treatments, exposures, results of a diagnostic test) and columns are the outcomes (ill or not, cured or not, disease present or absent). This chapter presents the analysis Analysis › Compare Groups › Contingency Table Tests: the chi-square test (with or without Yates' correction), Fisher's exact test, the chi-square test for trend, and the effect measures of 2×2 tables (relative risk, difference between risks, number needed to treat, odds ratio, sensitivity, specificity and predictive values) with their confidence intervals. The examples use the sample data of the Start window; the values quoted were recomputed with Variance's code.
Contingency Table Tests#
This analysis tests the association between the rows and the columns of a Contingency table (does the proportion of events differ between groups?) and, for a 2×2 table, measures the size of this association. It offers Fisher's exact test (2×2), Pearson's chi-square test (any table size), its variant with Yates' continuity correction (2×2) and the Cochran-Armitage chi-square test for trend (ordered groups).
When to use it#
- The data are counts of independent subjects classified by two categorical criteria, each subject counting in a single cell. Examples: treatment or placebo × ill or not; exposure × case or control; test result × disease.
- 2×2 table: Fisher's exact test is Variance's default choice; it remains valid with small counts. The chi-square test is an approximation that is suitable when the expected counts are large enough.
- Larger table (r × c): chi-square test (Variance computes Fisher's exact test only for 2×2 tables).
- Ordered groups (increasing doses, age classes) and a binary outcome: the test for trend, more powerful than the overall chi-square when the proportion changes steadily.
- Not suitable for paired proportions (same subject before and after, matched pairs): use McNemar's test (section "McNemar's Test (Paired Proportions)" below). Not suitable either for percentages, means or continuous measurements.
Assumptions and checks#
- Independence: each subject appears only once; subjects are independent (no repeated measurements, no clusters: patients of the same ward, eyes of the same patient).
- Counts, not percentages: Variance rejects negative or non-integer values ("contingency tables must contain counts (non-negative integers)").
- Chi-square: the expected counts (not the observed ones) must be large enough; the usual rule (Cochran) asks for expected counts of at least 5 (or at least 1, with no more than 20% of cells below 5, for larger tables). Variance shows the "Expected counts" tab and the warning "Some expected counts are below 5: the chi-square approximation may be inaccurate." when an expected count is below 5.
- Fisher's exact test: it conditions on the row and column totals; it is exact under this condition, and somewhat conservative when only one set of totals is fixed by the design.
- Sampling design: the relative risk and the difference between risks assume that the proportions of each row estimate risks (cohort study or trial); in a case-control study (numbers of patients fixed by the investigator), only the odds ratio can be interpreted. Predictive values depend on the prevalence of the disease in the sample.
Step by step in Variance#
- Create a Contingency table ("Start" window, "Contingency" type). To follow the example: "an example" then "Treatment and outcome (2×2)".
- Enter the counts: one row per group (row label = name of the group), one column per outcome (data set title = name of the outcome). For the effect measures of a 2×2 table, the orientation matters:
- risks and odds ratio: row 1 = exposed or treated group, row 2 = reference group; column 1 = event (ill, death…), column 2 = no event;
- sensitivity and specificity: row 1 = positive test, row 2 = negative test; column 1 = disease present, column 2 = disease absent. A row containing an empty cell is ignored.
- Analysis › Compare Groups › Contingency Table Tests.
- "Main calculations" tab:
- "Test": "Fisher's exact test for 2×2, chi-square otherwise" (default), "Fisher's exact test (2×2)", "Chi-square with Yates' continuity correction", "Chi-square" or "Chi-square test for trend";
- "P value": "Two-tailed" (default), "One-tailed" or "One-tailed (other direction)"; this option only concerns Fisher's exact test;
- "Effect size (2×2)": "Relative risk, difference between proportions, NNT" (default), "Odds ratio" or "Diagnostic measures (sensitivity, specificity, predictive values)".
- "Options" tab: "Method for proportions" ("Wilson score (recommended)", "Clopper-Pearson (exact)" or "Wald"), "Confidence level (%)", "Significance level (alpha)", significant digits and P value format.
- "Data sets" tab: the columns (outcomes) analyzed. OK.
Rules applied: with the default choice, a 2×2 table gets Fisher's test and a larger table the uncorrected chi-square; "Fisher's exact test (2×2)" on a larger table also gives the uncorrected chi-square; Yates' correction is applied only to 2×2 tables (on a larger table, the title "Chi-square with Yates' correction" is shown but the chi-square is not corrected); the test for trend requires at least three rows and exactly two columns.
How it is calculated#
Notation: O_ij observed count, R_i total of row i, C_j total of column j, N grand total; for a 2×2 table:
event no event total
row 1 a b a + b
row 2 c d c + d
total a + c b + d N
Pearson's chi-square (r × c table):
E_ij = R_i · C_j / N expected count under independence
χ² = Σ_i Σ_j (O_ij − E_ij)² / E_ij df = (r − 1)(c − 1)
P = Prob( χ²(df) ≥ χ² )
A row or column whose total is zero carries no information: its expected counts are 0, it is left out of the sum, and r and c count only the rows and columns with a nonzero total. With fewer than two such rows or columns, the test cannot be computed.
Yates' continuity correction (2×2 tables only):
χ²_Yates = Σ [ max(0, |O_ij − E_ij| − 0.5) ]² / E_ij df = 1
The P value of the chi-square (corrected or not) is always the upper tail of the chi-square distribution, which ignores the direction of the difference: the "P value" option does not change it.
Fisher's exact test (2×2 table). With the row and column totals fixed, the number X of events in row 1 follows a hypergeometric distribution:
Prob(X = k) = C(a + c, k) · C(b + d, a + b − k) / C(N, a + b)
for max(0, (a + c) − (c + d)) ≤ k ≤ min(a + b, a + c)
two-tailed P = Σ Prob(X = k) over the k such that Prob(X = k) ≤ Prob(X = a) × (1 + 10⁻⁷)
"One-tailed" P = Prob(X ≥ a) (more events than expected in row 1: OR > 1)
"One-tailed (other direction)" P = Prob(X ≤ a) (fewer events: OR < 1)
C(n, k) is the number of combinations. The two-tailed P value is thus the sum of the probabilities of all tables as likely as or less likely than the observed table (the "method of small probabilities", the relative tolerance of 10⁻⁷ avoiding excluding a table of equal probability through a rounding error); it is not twice the one-tailed P value, and programs that double the one-tailed P value give a different result.
Chi-square test for trend (Cochran-Armitage). Rows receive the scores s_i = 1, 2, …, r in table order; x_i is the count in column 1 (events) of row i and n_i the row total:
p̄ = Σ x_i / N
T = Σ s_i · (x_i − n_i · p̄)
Var = p̄ · (1 − p̄) · [ Σ n_i · s_i² − (Σ n_i · s_i)² / N ]
χ²_trend = T² / Var df = 1 P = Prob( χ²(1) ≥ χ²_trend )
(without continuity correction; the P value is two-sided with respect to the direction of the trend). When Var = 0 (no event, only events, or every subject in a single row), the test is not defined and Variance does not compute it; nor for an empty table.
Effect measures of a 2×2 table. z is the 1 − (1 − C)/2 quantile of the normal distribution (1.96 for C = 95%). With p1 = a/(a + b) and p2 = c/(c + d), the risks in rows 1 and 2:
Relative risk RR = p1 / p2
CI (Katz log method): SE(ln RR) = √( 1/a − 1/(a + b) + 1/c − 1/(c + d) )
exp( ln RR ± z · SE(ln RR) )
Reciprocal of RR 1/RR, CI = (1/upper limit ; 1/lower limit)
Risk difference D = p1 − p2 ("Attributable risk (difference)")
CI (Newcombe's hybrid score, from the Wilson intervals [l1 ; u1] of p1
and [l2 ; u2] of p2):
lower limit = D − √( (p1 − l1)² + (u2 − p2)² )
upper limit = D + √( (u1 − p1)² + (p2 − l2)² )
Number needed to treat (or harm) NNT = 1 / |D| (no CI)
Odds ratio OR = (a · d) / (b · c)
CI (Woolf logit method): SE(ln OR) = √( 1/a + 1/b + 1/c + 1/d )
exp( ln OR ± z · SE(ln OR) )
if a cell is 0: 0.5 is added to all four cells for the CI (Haldane-Anscombe)
The interval of the risk difference always uses Wilson intervals, whatever the "Method for proportions" choice. If a or c is 0, the CI of the relative risk cannot be computed (no correction is applied to the RR). With a zero cell, Variance shows the raw odds ratio a·d/(b·c) (0, or an empty cell when it is infinite) with the CI computed on the corrected cells: the two are then not consistent.
Diagnostic measures (row 1 = positive test, column 1 = disease present):
Sensitivity a / (a + c)
Specificity d / (b + d)
Positive predictive value a / (a + b)
Negative predictive value d / (c + d)
Likelihood ratio sensitivity / (1 − specificity) (positive ratio, no CI)
Confidence interval of a proportion p = x/n ("Method for proportions"):
Wilson ("Wilson score") : center = (p + z²/(2n)) / (1 + z²/n)
half-width = z / (1 + z²/n) · √( p(1 − p)/n + z²/(4n²) )
(Wilson score without continuity correction, bounded to [0 ; 1])
Clopper-Pearson (exact) : lower limit = α/2 quantile of the Beta(x, n − x + 1) distribution (0 if x = 0)
upper limit = 1 − α/2 quantile of the Beta(x + 1, n − x) distribution (1 if x = n)
with α = 1 − C
Wald : p ± z · √( p(1 − p)/n ), bounded to [0 ; 1]
The Wilson interval is recommended (Brown, Cai and DasGupta, 2001); the Clopper-Pearson interval guarantees at least the stated level but is wider; the Wald interval is not recommended for small samples and proportions close to 0 or 1.
Reading the results#
"Contingency results" tab:
- "Input table";
- Fisher's test: "P value", "Significance code", "Sides of the test" ("Two-sided" or "One-sided") and "Statistically significant (P < α)?";
- chi-square: "Chi-square", "df", "P value", "Significance code" and "Statistically significant (P < α)?";
- trend: "Chi-square", "df" (1), "P value", "Significance code" and "Is there a significant trend (P < α)?".
The P value answers the question: if the proportions were the same in all rows (no association), what would be the probability of observing an association at least as strong? A large P value does not prove the absence of association: look at the CI of the effect measure.
"Effect size" tab (2×2 tables), columns "Value" and "95% CI":
- "Relative risk" and "1 / relative risk": RR < 1 means a lower risk in row 1; a CI that contains 1 is consistent with no effect;
- "Attributable risk (difference)": p1 − p2, as a proportion (−0.17 = 17 points less in row 1);
- "Number needed to treat (or harm)": number of subjects to treat (row 1 rather than row 2) to prevent, or cause, one more event; it is a number "to treat" when the event prevented is undesirable, "to harm" otherwise;
- "Odds ratio" (and "1 / odds ratio" with the "Odds ratio" option);
- "Sensitivity", "Specificity", "Positive predictive value", "Negative predictive value", "Likelihood ratio".
"Expected counts" tab (chi-square): counts expected under independence. Output table "Row percentages": for each row, the percentage of its total in each column; it can be graphed directly (Plot These Results button).
The last tab, "Narrative results", states the test in sentences ("Are the rows and the columns associated?", or the question of the trend for the test for trend) with the P value, the chance of an association this strong if rows and columns were independent, the conclusion and, for a 2 × 2 table, the measures of the effect with their confidence intervals.
Worked example#
Sample data "Treatment and outcome (2×2)":
Disease No disease Total
Treated 15 85 100
Placebo 32 68 100
Total 47 153 200
Risks: p1 = 15/100 = 0.15 (treated), p2 = 32/100 = 0.32 (placebo).
Fisher's exact test (default choice). With the totals fixed (100 and 47), Prob(X = 15) = C(47, 15)·C(153, 85)/C(200, 100) = 0.002384. Summing the probabilities of the tables as likely or less likely gives the two-tailed P value: P = 0.0072. With "One-tailed (other direction)" (fewer events among treated patients), P = Prob(X ≤ 15) = 0.0036; with "One-tailed", P = Prob(X ≥ 15) = 0.9988.
Chi-square ("Chi-square"): the expected counts are 23.5 and 76.5 in each row.
χ² = 2 × [ (15 − 23.5)²/23.5 + (85 − 76.5)²/76.5 ] = 2 × (3.0745 + 0.9444) = 8.038
df = 1 P = 0.0046
Yates: χ² = 2 × [ 8.0²/23.5 + 8.0²/76.5 ] = 2 × (2.7234 + 0.8366) = 7.120 P = 0.0076
Effect measures (default choice):
RR = 0.15 / 0.32 = 0.4688
SE(ln RR) = √(1/15 − 1/100 + 1/32 − 1/100) = 0.27914
95% CI = exp(ln 0.4688 ± 1.96 × 0.27914) = exp(−1.3048 ; −0.2106) = [0.271 ; 0.810]
D = 0.15 − 0.32 = −0.17
Wilson: 15/100 → [0.0931 ; 0.2328] 32/100 → [0.2367 ; 0.4166]
lower limit = −0.17 − √( (0.15 − 0.0931)² + (0.4166 − 0.32)² ) = −0.2822
upper limit = −0.17 + √( (0.2328 − 0.15)² + (0.32 − 0.2367)² ) = −0.0525
NNT = 1 / 0.17 = 5.88
OR = (15 × 68) / (85 × 32) = 0.375
SE(ln OR) = √(1/15 + 1/85 + 1/32 + 1/68) = 0.35269
95% CI = exp(−0.9808 ± 1.96 × 0.35269) = [0.188 ; 0.749]
Variance shows in the "Effect size" tab:
Value 95% CI
Relative risk 0.4688 0.2712 to 0.8101
1 / relative risk 2.133 1.234 to 3.687
Attributable risk (difference) -0.17 -0.2822 to -0.05252
Number needed to treat (or harm) 5.882
Odds ratio 0.375 0.1879 to 0.7486
About 6 patients must be treated to prevent one case of disease.
Diagnostic measures. For a table whose rows are "Test positive" and "Test negative" and whose columns are "Disease" and "No disease", with counts 45, 15 (row 1) and 5, 135 (row 2), the option "Diagnostic measures (sensitivity, specificity, predictive values)" gives (Wilson CIs): sensitivity 45/50 = 0.90 (0.786 to 0.957), specificity 135/150 = 0.90 (0.842 to 0.938), positive predictive value 45/60 = 0.75 (0.628 to 0.842), negative predictive value 135/140 = 0.964 (0.919 to 0.985), likelihood ratio 0.90/0.10 = 9.
Test for trend. For three ordered groups "Low", "Medium", "High" with 10, 18 and 27 events out of 100 subjects respectively (columns "Event" and "No event"):
p̄ = 55/300 = 0.18333
T = 1 × (10 − 18.333) + 2 × (18 − 18.333) + 3 × (27 − 18.333) = 17.0
Var = 0.18333 × 0.81667 × (1,400 − 600²/300) = 0.149722 × 200 = 29.944
χ²_trend = 17.0² / 29.944 = 9.651 df = 1 P = 0.0019
The overall chi-square of the same table is 9.662 with 2 df (P = 0.0080): almost all of the association is explained by the linear trend, which the trend test detects with a single degree of freedom.
Reporting#
- "Disease occurred in 15% of treated patients versus 32% under placebo (two-tailed Fisher's exact test, P = 0.007); relative risk 0.47 (95% CI 0.27 to 0.81), risk difference −17 percentage points (95% CI −28 to −5), that is about 6 patients to treat to prevent one case."
- "The proportion of events increased with the dose (Cochran-Armitage chi-square test for trend, χ² = 9.65, df = 1, P = 0.002)."
- Diagnosis: "sensitivity 90% (Wilson 95% CI 79 to 96%), specificity 90% (84 to 94%)."
Always state the test (Fisher, chi-square with or without correction), whether P is one- or two-tailed, and the method of the confidence intervals.
Common pitfalls#
- Entering percentages or means instead of counts.
- Counting the same subject several times (several lesions, several visits): the observations are no longer independent.
- Using the chi-square test with small expected counts: prefer the exact test (2×2) or merge categories in a justified way.
- Choosing the test from the P value obtained (Fisher, Yates or plain chi-square give different P values): decide before the analysis. Yates' correction is conservative.
- Swapping rows and columns: the relative risk, the risk difference, sensitivity and predictive values change direction or value; check the orientation described above.
- Computing a relative risk in a case-control study: only the odds ratio makes sense. The odds ratio approximates the relative risk only when the event is rare.
- Generalizing predictive values: they depend on the prevalence in the sample.
- Interpreting the NNT without an interval: when the CI of the difference contains 0, the CI of the NNT contains infinity; Variance does not compute this interval.
- Test for trend: it uses the scores 1, 2, 3… in row order; arrange the groups in their natural order, and remember that unequally spaced doses are not taken into account.
- Paired proportions (before/after on the same subjects): this analysis is not suitable; use McNemar's test (next section).
McNemar's Test (Paired Proportions)#
When each subject is classified twice (before and after a treatment, by two diagnostic tests, or the two members of a matched pair), the two proportions of "positives" are not independent: the chi-square and Fisher tests are not suitable. McNemar's test compares these paired proportions using only the discordant pairs.
When to use it#
- Two binary measurements on the same subjects: positive or negative before and after, two diagnostic tests on the same patients, case and control of the same pair.
- Not suitable for independent groups (chi-square or Fisher, previous section) nor for more than two conditions (Cochran's Q test, which Variance does not offer).
Step by step in Variance#
- Create a Contingency table with two rows and two columns that counts pairs: the rows are the first condition (row 1 "+", row 2 "−"), the columns the second (column 1 "+", column 2 "−"). Each subject (or each pair) is counted once.
- Choose Analysis › Compare Groups › McNemar's Test (Paired Proportions).
- Options tab: "P value": "Exact (binomial test on the discordant pairs)" (default) or "Chi-square (McNemar)"; "Continuity correction of the chi-square (Edwards)" (checked, grayed out with the exact test); confidence level, α, significant digits and P value style.
- OK. Only the first two filled rows of the first two analyzed columns are used.
How it is calculated#
table of pairs: second + second −
first + a b
first − c d n = a + b + c + d
discordant pairs: b (+ then −) and c (− then +)
exact P = two-sided binomial test of b successes out of b + c trials, probability 1/2
χ² = (|b − c| − 1)² / (b + c), 0 if b = c (without correction: (b − c)² / (b + c)), 1 df
odds ratio of the discordant pairs = b / c; exact CI: p / (1 − p) at the limits of
the Clopper-Pearson interval of p = b / (b + c)
proportions of positives: p₁ = (a + b) / n (first), p₂ = (a + c) / n (second)
difference p₁ − p₂ = (b − c) / n ; SE = √[ b + c − (b − c)² / n ] / n ; Wald CI ± z·SE
The concordant pairs (a and d) bring no information about the difference: they only enter the proportions and the sample size. The exact test is valid whatever the number of discordant pairs; the chi-square requires b + c to be large enough (at least 10 to 25 depending on the authors).
Reading the results#
"McNemar's test" tab: "Input table"; "Discordant pairs" (b and c, named by their row and column); "Test": "Exact P value (binomial, two-tailed)", "Chi-square, df = 1 (with continuity correction)", "P value (chi-square)", "P value used" (the P value kept for the next two rows), "Significance code" and "Significantly different (P < α)?"; "Effect size": "Odds ratio (b / c)" and its exact CI, the proportion of positives in each condition, "Difference (first − second)" and its CI; "Number of pairs".
Worked example#
Fifty patients are tested by two methods: 20 are positive on both, 10 on the first only, 2 on the second only and 18 negative on both (row 1: 20 and 10; row 2: 2 and 18).
b = 10, c = 2, b + c = 12
exact P = 2 × P(X ≤ 2 | 12, 0.5) = 2 × (1 + 12 + 66) / 4096 = 0.0386
corrected χ² = (8 − 1)² / 12 = 4.083; P = 0.0433 (without correction: 5.333; P = 0.0209)
odds ratio = 10 / 2 = 5; Clopper-Pearson of 10/12: 0.5159 to 0.9791 → CI 1.066 to 46.93
p₁ = 30/50 = 0.60; p₂ = 22/50 = 0.44; difference = 8/50 = 0.16
SE = √(12 − 64/50) / 50 = 0.06548; 95% CI = 0.16 ± 1.96 × 0.06548 = 0.032 to 0.288
The first method gives more positives (60% versus 44%). The CI of the odds ratio is very wide: twelve discordant pairs say little about the size of the gap.
Reporting#
"The proportions of positives were compared with the exact McNemar test (Variance): 60% with method A versus 44% with method B (difference 16 points, 95% CI 3 to 29 points; 10 versus 2 discordant pairs, P = 0.039)."
Common pitfalls#
- Analyzing paired data with the chi-square or Fisher test.
- Counting subjects instead of pairs: each pair appears only once in the table.
- Forgetting that only the number of discordant pairs matters: with very few discordant pairs, the test cannot show anything, whatever the number of concordant pairs.
References#
Books:
- Agresti A. Categorical Data Analysis, 3rd ed. Wiley, 2013.
- Altman DG. Practical Statistics for Medical Research. Chapman & Hall, 1991.
- Motulsky H. Intuitive Biostatistics, 4th ed. Oxford University Press, 2018.
- Zar JH. Biostatistical Analysis, 5th ed. Pearson Prentice Hall, 2010.
Articles:
- Fisher RA. On the interpretation of χ² from contingency tables, and the calculation of P. Journal of the Royal Statistical Society 1922;85:87-94.
- Yates F. Contingency tables involving small numbers and the χ² test. Supplement to the Journal of the Royal Statistical Society 1934;1:217-235.
- Cochran WG. Some methods for strengthening the common χ² tests. Biometrics 1954;10:417-451.
- Armitage P. Tests for linear trends in proportions and frequencies. Biometrics 1955;11:375-386.
- Campbell I. Chi-squared and Fisher-Irwin tests of two-by-two tables with small sample recommendations. Statistics in Medicine 2007;26:3661-3675.
- Katz D, Baptista J, Azen SP, Pike MC. Obtaining confidence intervals for the risk ratio in cohort studies. Biometrics 1978;34:469-474.
- Woolf B. On estimating the relation between blood group and disease. Annals of Human Genetics 1955;19:251-253.
- Haldane JBS. The estimation and significance of the logarithm of a ratio of frequencies. Annals of Human Genetics 1956;20:309-311.
- Newcombe RG. Interval estimation for the difference between independent proportions: comparison of eleven methods. Statistics in Medicine 1998;17:873-890.
- Wilson EB. Probable inference, the law of succession, and statistical inference. Journal of the American Statistical Association 1927;22:209-212.
- Clopper CJ, Pearson ES. The use of confidence or fiducial limits illustrated in the case of the binomial. Biometrika 1934;26:404-413.
- Brown LD, Cai TT, DasGupta A. Interval estimation for a binomial proportion. Statistical Science 2001;16:101-133.
- Laupacis A, Sackett DL, Roberts RS. An assessment of clinically useful measures of the consequences of treatment. New England Journal of Medicine 1988;318:1728-1733.
- Altman DG. Confidence intervals for the number needed to treat. BMJ 1998;317:1309-1312.
- McNemar Q. Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika 1947;12:153-157.
- Edwards AL. Note on the "correction for continuity" in testing the significance of the difference between correlated proportions. Psychometrika 1948;13:185-187.