Categorical Data (Chi-square & Fisher)
Mutation status, treatment response, cell type, and sex are categories. The data for two of them are counts in a contingency table. This page asks whether a mutation is associated with response to treatment in 50 patients. It tests the table, then reports how far the response proportions are apart.
When to use each test
Section titled “When to use each test”Both tests start from the same null model: the two variables are independent, so the response proportion is the same with and without the mutation.
The chi-square test compares each observed count with the count expected under independence. Its p-value comes from a large-sample approximation, which needs expected counts that are not small. A common working rule asks for an expected count of at least 5 in every cell.
Fisher’s exact test computes the p-value from the exact distribution of the table, with the row and column totals held fixed. It needs no minimum count, and it is the usual choice for a 2x2 table that fails the rule.
Get the data
Section titled “Get the data”Download patients.csv into your working directory. The invented table has 50 rows and two columns: mutation (mutant or wildtype) and response (responder or non_responder). Each row is a different patient.
The code puts mutant patients in the first row of the table and responders in the first column. That orientation sets the direction of every estimate on this page: each one compares response in mutant patients with response in wild-type patients.
library(ggplot2)
patients <- read.csv("patients.csv")patients$mutation <- factor(patients$mutation, levels = c("mutant", "wildtype"))patients$response <- factor(patients$response, levels = c("responder", "non_responder"))dir.create("outputs", showWarnings = FALSE)
counts <- table(mutation = patients$mutation, response = patients$response)countsprop.table(counts, margin = 1) responsemutation responder non_responder mutant 18 7 wildtype 9 16 responsemutation responder non_responder mutant 0.72 0.28 wildtype 0.36 0.64from pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdfrom scipy import statsfrom statsmodels.stats.proportion import confint_proportions_2indep
patients = pd.read_csv("patients.csv")output = Path("outputs")output.mkdir(exist_ok=True)
counts = pd.crosstab(patients["mutation"], patients["response"])counts = counts.loc[["mutant", "wildtype"], ["responder", "non_responder"]]proportions = counts.div(counts.sum(axis=1), axis=0)print(counts)print(proportions)response responder non_respondermutationmutant 18 7wildtype 9 16response responder non_respondermutationmutant 0.72 0.28wildtype 0.36 0.64Among the 25 mutant patients, 18 responded, a proportion of 0.72. Among the 25 wild-type patients, 9 responded, a proportion of 0.36.
Chi-square test
Section titled “Chi-square test”The test statistic sums, over the four cells, the squared gap between the observed and the expected count, divided by the expected count. The expected counts come from the row and column totals alone, so print them to see what independence would look like and to check the rule of 5.
chi_square <- chisq.test(counts)cat(sprintf("Chi-square = %.3f, df = %.0f, p = %.4f\n", chi_square$statistic, chi_square$parameter, chi_square$p.value))chi_square$expectedChi-square = 5.153, df = 1, p = 0.0232 responsemutation responder non_responder mutant 13.5 11.5 wildtype 13.5 11.5chi_square = stats.chi2_contingency(counts)expected = pd.DataFrame(chi_square.expected_freq, index=counts.index, columns=counts.columns)print(f"Chi-square = {chi_square.statistic:.3f}, df = {chi_square.dof}, " f"p = {chi_square.pvalue:.4f}")print(expected)Chi-square = 5.153, df = 1, p = 0.0232response responder non_respondermutationmutant 13.5 11.5wildtype 13.5 11.5With 27 responders among 50 patients, independence would put 13.5 responders and 11.5 non-responders in each group of 25. All four expected counts are well above 5, so the approximation is acceptable for this table.
The statistic is 5.153 on 1 degree of freedom, and p = 0.0232. If response were independent of mutation, a table at least this far from the expected counts would appear in about 2.3% of studies of this size. Both functions apply Yates’ continuity correction to a 2x2 table by default, which is why the two languages agree to every printed digit. Without the correction, set by correct = FALSE in R and correction=False in SciPy, the statistic is larger and the p-value smaller.
A stacked bar of the response proportions shows the gap that the test responds to. position_fill(reverse = TRUE) puts the first level, the responders, at the bottom of each bar in R, where pandas draws the first column.
response_colors <- c(responder = "#4c72b0", non_responder = "#c9c9c9")bar_plot <- ggplot(patients, aes(x = mutation, fill = response)) + geom_bar(position = position_fill(reverse = TRUE)) + scale_fill_manual(values = response_colors) + labs(x = NULL, y = "Proportion of patients", fill = "Response", title = "Response by mutation status", subtitle = sprintf("Chi-square test, p = %.3f", chi_square$p.value)) + theme_minimal(base_size = 13)ggsave("outputs/categorical-bar-r.png", bar_plot, width = 5.5, height = 4, dpi = 150)
figure, axes = plt.subplots(figsize=(5.5, 4))proportions.plot(kind="bar", stacked=True, color=["#4c72b0", "#c9c9c9"], ax=axes)axes.set_xlabel("")axes.set_ylabel("Proportion of patients")axes.set_title("Response by mutation status\n" f"Chi-square test, p = {chi_square.pvalue:.3f}")axes.tick_params(axis="x", rotation=0)axes.legend(title="Response", bbox_to_anchor=(1.02, 1), loc="upper left")figure.tight_layout()figure.savefig(output / "categorical-bar-python.png", dpi=150)plt.close(figure)
Fisher’s exact test
Section titled “Fisher’s exact test”Fisher’s test keeps the row and column totals fixed and sums the probabilities of every table that is as unlikely as the observed one or less likely. Its effect measure is the odds ratio, and the two languages report different estimates of it, so the code prints both.
exact <- fisher.test(counts)sample_odds_ratio <- (counts[1, 1] * counts[2, 2]) / (counts[1, 2] * counts[2, 1])cat(sprintf("Fisher exact p = %.4f\n", exact$p.value))cat(sprintf("Conditional odds ratio %.3f, 95%% CI [%.2f, %.2f]\n", exact$estimate, exact$conf.int[1], exact$conf.int[2]))cat(sprintf("Sample odds ratio %.3f\n", sample_odds_ratio))Fisher exact p = 0.0222Conditional odds ratio 4.422, 95% CI [1.20, 18.03]Sample odds ratio 4.571exact = stats.fisher_exact(counts)conditional = stats.contingency.odds_ratio(counts.to_numpy(), kind="conditional")odds_interval = conditional.confidence_interval(0.95)print(f"Fisher exact p = {exact.pvalue:.4f}")print(f"Conditional odds ratio {conditional.statistic:.3f}, " f"95% CI [{odds_interval.low:.2f}, {odds_interval.high:.2f}]")print(f"Sample odds ratio {exact.statistic:.3f}")Fisher exact p = 0.0222Conditional odds ratio 4.422, 95% CI [1.20, 18.03]Sample odds ratio 4.571The exact p-value is 0.0222, close to the chi-square result.
The odds of response are 18 to 7 in mutant patients and 9 to 16 in wild-type patients. Their ratio, (18 × 16) / (7 × 9) = 4.571, is the sample odds ratio. R’s fisher.test() does not report that number. It reports the conditional maximum likelihood estimate, 4.422, which comes from the same fixed-totals distribution as the exact p-value. SciPy’s fisher_exact() returns the sample odds ratio as its statistic, and odds_ratio() with kind="conditional" returns the estimate that R prints. Say which one you report.
The interval of the conditional estimate runs from 1.20 to 18.03. Fifty patients leave the odds ratio poorly determined: values just above 1 and values near 18 are both compatible with this table.
An odds ratio of 4.4 does not mean that mutant patients are 4.4 times as likely to respond. Odds and proportions are different scales, and the two response proportions, 0.72 and 0.36, differ by a factor of 2.
Difference in response proportions
Section titled “Difference in response proportions”The difference between the two response proportions is the effect that most readers want, because it stays in the units of the question. prop.test() in R reads the first column of the table as the successes, here the responders, and returns the proportion of each row with an interval for their difference. confint_proportions_2indep() in statsmodels takes the two counts and the two group sizes.
Both calls below name the Wald interval: the difference plus or minus 1.96 standard errors, where the standard error combines the binomial variance of each proportion. The defaults differ between the languages. prop.test() adds a continuity correction unless correct = FALSE, and confint_proportions_2indep() computes Newcombe’s score interval unless method="wald".
difference <- prop.test(counts, correct = FALSE)cat(sprintf("Response: mutant %.2f, wildtype %.2f\n", difference$estimate[1], difference$estimate[2]))cat(sprintf("Difference %.2f, 95%% Wald CI [%.3f, %.3f]\n", difference$estimate[1] - difference$estimate[2], difference$conf.int[1], difference$conf.int[2]))Response: mutant 0.72, wildtype 0.36Difference 0.36, 95% Wald CI [0.102, 0.618]responders = counts["responder"]group_sizes = counts.sum(axis=1)response = responders / group_sizeswald_low, wald_high = confint_proportions_2indep( responders["mutant"], group_sizes["mutant"], responders["wildtype"], group_sizes["wildtype"], method="wald", compare="diff")print(f"Response: mutant {response['mutant']:.2f}, " f"wildtype {response['wildtype']:.2f}")print(f"Difference {response['mutant'] - response['wildtype']:.2f}, " f"95% Wald CI [{wald_low:.3f}, {wald_high:.3f}]")Response: mutant 0.72, wildtype 0.36Difference 0.36, 95% Wald CI [0.102, 0.618]Response is 36 percentage points more frequent in mutant patients, and differences from 10 to 62 percentage points are compatible with the data. The interval excludes zero and is still wide: 25 patients per group cannot tell a modest advantage from a very large one.
The Wald interval rests on the same large-sample reasoning as the chi-square test. Its coverage falls below 95% when a cell count is small or a proportion is close to 0 or 1, which is not the case for this table.
Mistakes to avoid
Section titled “Mistakes to avoid”Give the tests the counts. A table of percentages has lost the number of patients, and the same two percentages are weak evidence in a small study and strong evidence in a large one.
Count each patient one time. Two biopsies from one patient are not two independent rows, and a table that includes both overstates the evidence.
Do not read the direction from the p-value. The chi-square and Fisher tests say that the table is hard to reconcile with independence. The proportions say which group responds more often and by how much.
Report the result
Section titled “Report the result”Give the counts, the difference with its interval, and then the test: “Response was more frequent in mutant patients (18 of 25, 72%) than in wild-type patients (9 of 25, 36%), a difference of 36 percentage points (95% Wald CI 10 to 62; Fisher’s exact test, p = 0.022).”
Scientific references
Section titled “Scientific references”Yates, 1934 describes the chi-square test for contingency tables with small counts and the continuity correction that R and SciPy apply to a 2x2 table.
Further reading
Section titled “Further reading”The risk measures page covers the risk difference, the risk ratio, and the odds ratio as measures of effect.
The R documentation of chisq.test() explains the expected counts, the continuity correction, and the simulated p-value for tables with small counts. The documentation of fisher.test() describes the conditional estimate of the odds ratio, and the documentation of prop.test() describes the interval for a difference of two proportions.
The SciPy documentation of odds_ratio() defines the sample and the conditional odds ratio and their intervals. The statsmodels documentation of confint_proportions_2indep() lists the interval methods for a difference, a ratio, and an odds ratio of two proportions.
The correlation page covers association between two numeric measurements.