Case-control Studies & Conditional Logistic Regression
A case-control study samples people by their outcome: the cases that arose in a source population, and a set of controls from the people who did not become cases. The design cannot estimate a risk unless the sampling fraction of the controls is known, and it can estimate an odds ratio. This page draws an unmatched and an individually matched sample from one simulated cohort, analyzes them with the 2x2 table, logistic regression, matched pairs and conditional logistic regression, and sets every odds ratio against the true value.
Get the data
Section titled “Get the data”Download ugib_unmatched.csv, ugib_matched.csv and ugib_overmatched.csv into your working directory. The three invented tables are samples from one simulated cohort of 120,000 adults aged 40 to 79 who were followed for five years. The exposure is regular use of a nonsteroidal anti-inflammatory drug (NSAID) at entry, and the outcome is a first upper gastrointestinal bleed. Each row is one person.
ugib_unmatched.csvholds every case and two controls per case drawn at random from the people without a bleed. Its columns areperson_id,case(1 for a bleed),nsaid(1 for regular use),age_band(40-49, 50-59, 60-69 or 70-79) andsex(F or M).ugib_matched.csvholds the same cases, each with two controls of the same age band and sex. Its columns areset_id, which numbers the matched sets,case,nsaid,age_bandandsex.ugib_overmatched.csvhas the same layout plusulcer(1 for a peptic ulcer during follow-up), and its controls also share the ulcer status of their case.
The unmatched and the matched table each have 1,482 rows, 494 cases and 988 controls, as the first output shows, and the overmatched table has the same size.
The cohort follows one causal order: age band and sex, then NSAID use, then a peptic ulcer during follow-up, then the bleed. In women NSAID use rises from 5% at age 40-49 to 55% at age 70-79, and men have half the odds of use. An ulcer occurs in 5% of people who do not use NSAIDs, and NSAID use multiplies its odds by 4. The log odds of a bleed is linear in age band, sex, NSAID use and ulcer status with no product term. Its odds ratios are 1.5, 2.5 and 4 for the three older age bands, 1.8 for men, 14.5 for an ulcer and 1.5 for NSAID use with ulcer status held fixed, and a woman aged 40-49 with neither NSAIDs nor an ulcer has a five-year risk of 0.06%. The estimand of every analysis below except the overmatched one is the total odds ratio of NSAID use given age band and sex, which includes the path through the ulcer. It has no closed form, so the code computes it from these parameters for each age band and sex, together with the true age effect and the risk of the reference group.
library(survival)library(ggplot2)
unmatched <- read.csv("ugib_unmatched.csv")matched <- read.csv("ugib_matched.csv")overmatched <- read.csv("ugib_overmatched.csv")dir.create("outputs", showWarnings = FALSE)print(head(matched, 4))cat(sprintf("Unmatched: %d cases and %d controls\n", sum(unmatched$case), sum(unmatched$case == 0)))cat(sprintf("Matched: %d sets, %d cases and %d controls\n", length(unique(matched$set_id)), sum(matched$case), sum(matched$case == 0)))age_or <- c(1, 1.5, 2.5, 4)strata_grid <- expand.grid(age = 1:4, male = 0:1, nsaid = 0:1)ulcer_odds <- 0.05 / 0.95 * 4^strata_grid$nsaidp_ulcer <- ulcer_odds / (1 + ulcer_odds)log_odds <- qlogis(0.0006) + log(age_or[strata_grid$age]) + log(1.8) * strata_grid$male + log(1.5) * strata_grid$nsaidrisk <- (1 - p_ulcer) * plogis(log_odds) + p_ulcer * plogis(log_odds + log(14.5))odds <- risk / (1 - risk)true_or <- odds[strata_grid$nsaid == 1] / odds[strata_grid$nsaid == 0]true_age_or <- odds[strata_grid$age == 4] / odds[strata_grid$age == 1]total_truth <- sprintf("%.2f to %.2f", min(true_or), max(true_or))cat(sprintf("True odds ratio of NSAID use given age band and sex: %s\n", total_truth))cat(sprintf("True odds ratio of age 70-79 against 40-49: %.2f to %.2f\n", min(true_age_or), max(true_age_or)))cat(sprintf("True risk, women 40-49 without NSAIDs: %.5f\n", risk[1])) set_id case nsaid age_band sex1 1 1 1 60-69 F2 1 0 0 60-69 F3 1 0 0 60-69 F4 2 1 1 70-79 MUnmatched: 494 cases and 988 controlsMatched: 494 sets, 494 cases and 988 controlsTrue odds ratio of NSAID use given age band and sex: 2.92 to 2.99True odds ratio of age 70-79 against 40-49: 3.86 to 3.96True risk, women 40-49 without NSAIDs: 0.00100from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport statsmodels.api as smimport statsmodels.formula.api as smffrom scipy import statsfrom scipy.special import expitfrom statsmodels.discrete.conditional_models import ConditionalLogitfrom statsmodels.stats.contingency_tables import mcnemar
unmatched = pd.read_csv("ugib_unmatched.csv")matched = pd.read_csv("ugib_matched.csv")overmatched = pd.read_csv("ugib_overmatched.csv")output = Path("outputs")output.mkdir(exist_ok=True)print(matched.head(4))print(f"Unmatched: {unmatched['case'].sum()} cases and " f"{(unmatched['case'] == 0).sum()} controls")print(f"Matched: {matched['set_id'].nunique()} sets, " f"{matched['case'].sum()} cases and " f"{(matched['case'] == 0).sum()} controls")age_or = np.array([1, 1.5, 2.5, 4])age_grid, male_grid, nsaid_grid = np.meshgrid( np.arange(4), [0, 1], [0, 1], indexing="ij")ulcer_odds = 0.05 / 0.95 * 4.0**nsaid_gridp_ulcer = ulcer_odds / (1 + ulcer_odds)log_odds = (np.log(0.0006 / 0.9994) + np.log(age_or[age_grid]) + np.log(1.8) * male_grid + np.log(1.5) * nsaid_grid)risk = ((1 - p_ulcer) * expit(log_odds) + p_ulcer * expit(log_odds + np.log(14.5)))odds = risk / (1 - risk)true_or = odds[:, :, 1] / odds[:, :, 0]true_age_or = odds[3] / odds[0]total_truth = f"{true_or.min():.2f} to {true_or.max():.2f}"print(f"True odds ratio of NSAID use given age band and sex: {total_truth}")print("True odds ratio of age 70-79 against 40-49: " f"{true_age_or.min():.2f} to {true_age_or.max():.2f}")print(f"True risk, women 40-49 without NSAIDs: {risk[0, 0, 0]:.5f}") set_id case nsaid age_band sex0 1 1 1 60-69 F1 1 0 0 60-69 F2 1 0 0 60-69 F3 2 1 1 70-79 MUnmatched: 494 cases and 988 controlsMatched: 494 sets, 494 cases and 988 controlsTrue odds ratio of NSAID use given age band and sex: 2.92 to 2.99True odds ratio of age 70-79 against 40-49: 3.86 to 3.96True risk, women 40-49 without NSAIDs: 0.00100The true total odds ratio lies between 2.92 and 2.99 across the eight combinations of age band and sex. It is lowest where the risk of a bleed is highest, because an odds ratio averaged over ulcer status is not collapsible, and each analysis below estimates one summary of these eight values. The true odds ratio of age 70-79 against 40-49 lies between 3.86 and 3.96 for the same reason, and the five-year risk of a woman aged 40-49 who does not use NSAIDs, over both ulcer states, is 0.00100. Age band and sex confound the crude comparison, because both NSAID use and the risk of a bleed rise with age. The tables are one draw from a fixed seed, so each estimate below carries the sampling error of a single study of this size, and a second draw would scatter around the truth about as widely as the intervals suggest.
The unmatched study
Section titled “The unmatched study”The unmatched sample is analyzed as a cohort table would be: the 2x2 table of NSAID use by case status, then a logistic model with age band and sex. Four helper functions compute each odds ratio with Wald limits on the log scale and print it beside the truth. The logistic regression page explains the model and its odds ratio, and the categorical data page covers the tests for a 2x2 table.
#' Turn a log odds ratio and its standard error into one result row.#'#' @param analysis Text that names the analysis.#' @param log_or The log odds ratio.#' @param se The standard error of the log odds ratio.#' @return A data frame with one row: the odds ratio and its 95% Wald#' limits.ResultRow <- function(analysis, log_or, se) { z <- qnorm(0.975) data.frame(analysis = analysis, odds_ratio = exp(log_or), lower = exp(log_or - z * se), upper = exp(log_or + z * se))}
#' Compute the odds ratio of the 2x2 table of NSAID use by case status.#'#' @param data A data frame with the 0/1 columns nsaid and case.#' @param analysis Text that names the analysis.#' @return One result row from ResultRow().TableOddsRatio <- function(data, analysis) { cells <- table(data$nsaid, data$case) log_or <- log(cells[2, 2] * cells[1, 1] / (cells[2, 1] * cells[1, 2])) ResultRow(analysis, log_or, sqrt(sum(1 / cells)))}
#' Take the NSAID odds ratio from a fitted model.#'#' @param fit A glm or clogit fit with a coefficient named nsaid.#' @param analysis Text that names the analysis.#' @return One result row from ResultRow().ModelOddsRatio <- function(fit, analysis) { ResultRow(analysis, coef(fit)[["nsaid"]], sqrt(vcov(fit)["nsaid", "nsaid"]))}
#' Print result rows beside the true odds ratio.#'#' @param rows A data frame of rows from ResultRow().#' @param truth Text that gives the true odds ratio.#' @return NULL, invisibly.PrintRows <- function(rows, truth) { cat(sprintf("%-36s %5.2f [%.2f, %.2f] truth %s\n", rows$analysis, rows$odds_ratio, rows$lower, rows$upper, truth), sep = "") invisible(NULL)}
print(addmargins(table(nsaid = unmatched$nsaid, case = unmatched$case)))unmatched_fit <- glm(case ~ nsaid + age_band + sex, family = binomial, data = unmatched)results <- rbind( TableOddsRatio(unmatched, "Unmatched, crude table"), ModelOddsRatio(unmatched_fit, "Unmatched, adjusted for age and sex"))PrintRows(results, total_truth) casensaid 0 1 Sum 0 837 258 1095 1 151 236 387 Sum 988 494 1482Unmatched, crude table 5.07 [3.96, 6.49] truth 2.92 to 2.99Unmatched, adjusted for age and sex 3.46 [2.58, 4.63] truth 2.92 to 2.99def result_row(analysis, log_or, se): """Turn a log odds ratio and its standard error into one result row.
Args: analysis: Text that names the analysis. log_or: The log odds ratio. se: The standard error of the log odds ratio.
Returns: A dictionary with the odds ratio and its 95% Wald limits. """ z = stats.norm.ppf(0.975) return {"analysis": analysis, "odds_ratio": np.exp(log_or), "lower": np.exp(log_or - z * se), "upper": np.exp(log_or + z * se)}
def table_odds_ratio(data, analysis): """Compute the odds ratio of the 2x2 table of NSAID use by case status.
Args: data: A data frame with the 0/1 columns nsaid and case. analysis: Text that names the analysis.
Returns: One result row from result_row(). """ cells = pd.crosstab(data["nsaid"], data["case"]) log_or = np.log(cells.loc[1, 1] * cells.loc[0, 0] / (cells.loc[1, 0] * cells.loc[0, 1])) return result_row(analysis, log_or, np.sqrt((1 / cells).to_numpy().sum()))
def model_odds_ratio(fit, analysis): """Take the NSAID odds ratio from a fitted model.
Args: fit: A statsmodels result with a coefficient named nsaid. analysis: Text that names the analysis.
Returns: One result row from result_row(). """ return result_row(analysis, fit.params["nsaid"], fit.bse["nsaid"])
def print_rows(rows, truth): """Print result rows beside the true odds ratio.
Args: rows: A list of rows from result_row(). truth: Text that gives the true odds ratio.
Returns: None. """ for row in rows: print(f"{row['analysis']:<36} {row['odds_ratio']:5.2f} " f"[{row['lower']:.2f}, {row['upper']:.2f}] truth {truth}")
print(pd.crosstab(unmatched["nsaid"], unmatched["case"], margins=True, margins_name="Sum"))unmatched_fit = smf.glm("case ~ nsaid + age_band + sex", data=unmatched, family=sm.families.Binomial()).fit()results = [ table_odds_ratio(unmatched, "Unmatched, crude table"), model_odds_ratio(unmatched_fit, "Unmatched, adjusted for age and sex"),]print_rows(results, total_truth)case 0 1 Sumnsaid0 837 258 10951 151 236 387Sum 988 494 1482Unmatched, crude table 5.07 [3.96, 6.49] truth 2.92 to 2.99Unmatched, adjusted for age and sex 3.46 [2.58, 4.63] truth 2.92 to 2.99Of the 494 cases 236 used NSAIDs, against 151 of the 988 controls. The crude odds ratio is 236 × 837 / (151 × 258) = 5.07, and its interval from 3.96 to 6.49 lies above the truth. Older people use NSAIDs more often and bleed more often, so the crude table credits NSAIDs with part of the effect of age. With age band and sex in the model the odds ratio is 3.46, with an interval from 2.58 to 4.63 that covers the true 2.92 to 2.99.
Why the intercept means nothing and the odds ratio survives
Section titled “Why the intercept means nothing and the odds ratio survives”The sample holds every case in the cohort and less than 1% of the people without a bleed. The investigator chose two controls per case, so the share of cases in the sample, one in three, says nothing about the risk in the cohort. The code reads the intercept of the adjusted model, the log odds of a bleed for a woman aged 40 to 49 who does not use NSAIDs, first as a risk and then after a correction by the sampling fraction of the controls.
cohort_size <- 120000case_count <- sum(unmatched$case)control_fraction <- sum(unmatched$case == 0) / (cohort_size - case_count)intercept <- coef(unmatched_fit)[["(Intercept)"]]cat(sprintf("Controls sampled: %.5f of the people without a bleed\n", control_fraction))cat(sprintf("Intercept %.3f, read as a risk %.3f\n", intercept, plogis(intercept)))cat(sprintf("Intercept + log(fraction) %.3f, as a risk %.5f, %s %.5f\n", intercept + log(control_fraction), plogis(intercept + log(control_fraction)), "truth", risk[1]))Controls sampled: 0.00827 of the people without a bleedIntercept -2.382, read as a risk 0.085Intercept + log(fraction) -7.178, as a risk 0.00076, truth 0.00100cohort_size = 120000case_count = unmatched["case"].sum()control_fraction = ((unmatched["case"] == 0).sum() / (cohort_size - case_count))intercept = unmatched_fit.params["Intercept"]shifted = intercept + np.log(control_fraction)print(f"Controls sampled: {control_fraction:.5f} of the people without " "a bleed")print(f"Intercept {intercept:.3f}, read as a risk {expit(intercept):.3f}")print(f"Intercept + log(fraction) {shifted:.3f}, as a risk " f"{expit(shifted):.5f}, truth {risk[0, 0, 0]:.5f}")Controls sampled: 0.00827 of the people without a bleedIntercept -2.382, read as a risk 0.085Intercept + log(fraction) -7.178, as a risk 0.00076, truth 0.00100Read as a risk, the intercept says that 8.5% of the reference group bleed within five years, 85 times the true 0.100%. Sampling multiplied the odds of being a case by 1 / 0.00827 in every group of the cohort, because every case entered the sample and 0.827% of the people without a bleed did. The intercept absorbed that factor, and adding log(0.00827) returns −7.178, a risk of 0.076% against the true 0.100%. The factor is the same for users and non-users, so it cancels from the odds ratio. That holds only when the controls are sampled without regard to exposure. Without a known sampling fraction the intercept has no use, and the odds ratio is the result.
The matched study, analyzed three ways
Section titled “The matched study, analyzed three ways”Individual matching gives each case controls that share its values of the matching factors, here two controls with the same age band and sex. The code fits three analyses to the matched sample: the crude 2x2 table, a logistic model with NSAID use alone, which ignores the matched sets, and conditional logistic regression. clogit() of survival and ConditionalLogit of statsmodels give each matched set its own baseline odds and fit a conditional likelihood that compares each case with its own controls, so the set baselines drop out without being estimated.
cat(sprintf("NSAID use: %.3f of random controls, %.3f of matched %s\n", mean(unmatched$nsaid[unmatched$case == 0]), mean(matched$nsaid[matched$case == 0]), "controls"))cat(sprintf("NSAID use: %.3f of cases\n", mean(matched$nsaid[matched$case == 1])))ignored_fit <- glm(case ~ nsaid, family = binomial, data = matched)conditional_fit <- clogit(case ~ nsaid + strata(set_id), data = matched)matched_rows <- rbind( TableOddsRatio(matched, "Matched, crude table"), ModelOddsRatio(ignored_fit, "Matched, logistic without the sets"), ModelOddsRatio(conditional_fit, "Matched, conditional logistic"))PrintRows(matched_rows, total_truth)results <- rbind(results, matched_rows[c(1, 3), ])NSAID use: 0.153 of random controls, 0.291 of matched controlsNSAID use: 0.478 of casesMatched, crude table 2.22 [1.78, 2.78] truth 2.92 to 2.99Matched, logistic without the sets 2.22 [1.78, 2.78] truth 2.92 to 2.99Matched, conditional logistic 2.81 [2.15, 3.67] truth 2.92 to 2.99random_controls = unmatched.loc[unmatched["case"] == 0, "nsaid"].mean()matched_controls = matched.loc[matched["case"] == 0, "nsaid"].mean()print(f"NSAID use: {random_controls:.3f} of random controls, " f"{matched_controls:.3f} of matched controls")print("NSAID use: " f"{matched.loc[matched['case'] == 1, 'nsaid'].mean():.3f} of cases")ignored_fit = smf.glm("case ~ nsaid", data=matched, family=sm.families.Binomial()).fit()conditional_fit = ConditionalLogit(matched["case"], matched[["nsaid"]], groups=matched["set_id"]).fit()matched_rows = [ table_odds_ratio(matched, "Matched, crude table"), model_odds_ratio(ignored_fit, "Matched, logistic without the sets"), model_odds_ratio(conditional_fit, "Matched, conditional logistic"),]print_rows(matched_rows, total_truth)results += [matched_rows[0], matched_rows[2]]NSAID use: 0.153 of random controls, 0.291 of matched controlsNSAID use: 0.478 of casesMatched, crude table 2.22 [1.78, 2.78] truth 2.92 to 2.99Matched, logistic without the sets 2.22 [1.78, 2.78] truth 2.92 to 2.99Matched, conditional logistic 2.81 [2.15, 3.67] truth 2.92 to 2.99Matched controls used NSAIDs more often than random controls, 29.1% against 15.3%, because they have the age of the cases and older people use NSAIDs more often. Of the cases, 47.8% used them. Ignoring the matching gives 2.22 from the table and from the logistic model alike, because a logistic model with one binary covariate reproduces the 2x2 table. That estimate is below the truth, on the side of 1, and its interval from 1.78 to 2.78 excludes the true 2.92 to 2.99. Matching made the controls resemble the cases in age and therefore in exposure, so a comparison that ignores the sets understates the difference between cases and controls. Conditional logistic regression returns 2.81 with an interval from 2.15 to 3.67, and R and Python agree to the printed digits.
Matching on age and sex did not remove the confounding by those factors. It moved the bias of the crude comparison from above the truth, 5.07 in the unmatched sample, to below it, 2.22, and only an analysis that accounts for the matching gives an interval that covers the truth.
The intuition from matched pairs
Section titled “The intuition from matched pairs”With one control per case, conditional logistic regression has a closed form that shows where its information comes from. The code keeps the first control of each set and cross-tabulates the NSAID use of each case against that of its control. A concordant pair, in which both or neither used NSAIDs, says nothing about the effect. The odds ratio is the number of pairs in which only the case was exposed divided by the number in which only the control was exposed, and the standard error of its log is the square root of the sum of the two reciprocals. McNemar’s test asks whether the two kinds of discordant pair are equally common, and the code turns off its continuity correction.
pairs <- matched[!duplicated(matched[c("set_id", "case")]), ]pairs <- pairs[order(pairs$set_id, -pairs$case), ]use <- c("no NSAID", "NSAID")pair_table <- table( case = factor(pairs$nsaid[pairs$case == 1], levels = 0:1, labels = use), control = factor(pairs$nsaid[pairs$case == 0], levels = 0:1, labels = use))print(pair_table)case_only <- pair_table["NSAID", "no NSAID"]control_only <- pair_table["no NSAID", "NSAID"]pair_fit <- clogit(case ~ nsaid + strata(set_id), data = pairs)pair_rows <- rbind( ResultRow("Pairs, ratio of discordant pairs", log(case_only / control_only), sqrt(1 / case_only + 1 / control_only)), ModelOddsRatio(pair_fit, "Pairs, conditional logistic"))PrintRows(pair_rows, total_truth)pair_test <- mcnemar.test(pair_table, correct = FALSE)cat(sprintf("McNemar chi-square %.2f, df 1, p = %.2g\n", pair_test$statistic, pair_test$p.value))results <- rbind(results, pair_rows[2, ]) controlcase no NSAID NSAID no NSAID 203 55 NSAID 142 94Pairs, ratio of discordant pairs 2.58 [1.89, 3.52] truth 2.92 to 2.99Pairs, conditional logistic 2.58 [1.89, 3.52] truth 2.92 to 2.99McNemar chi-square 38.42, df 1, p = 5.7e-10pairs = matched.drop_duplicates(["set_id", "case"])pairs = pairs.sort_values(["set_id", "case"], ascending=[True, False])use = np.array(["no NSAID", "NSAID"])pair_table = pd.crosstab( pd.Categorical(use[pairs.loc[pairs["case"] == 1, "nsaid"]], use), pd.Categorical(use[pairs.loc[pairs["case"] == 0, "nsaid"]], use), rownames=["case"], colnames=["control"])print(pair_table)case_only = pair_table.loc["NSAID", "no NSAID"]control_only = pair_table.loc["no NSAID", "NSAID"]pair_fit = ConditionalLogit(pairs["case"], pairs[["nsaid"]], groups=pairs["set_id"]).fit()pair_rows = [ result_row("Pairs, ratio of discordant pairs", np.log(case_only / control_only), np.sqrt(1 / case_only + 1 / control_only)), model_odds_ratio(pair_fit, "Pairs, conditional logistic"),]print_rows(pair_rows, total_truth)pair_test = mcnemar(pair_table, exact=False, correction=False)print(f"McNemar chi-square {pair_test.statistic:.2f}, df 1, " f"p = {pair_test.pvalue:.2g}")results.append(pair_rows[1])control no NSAID NSAIDcaseno NSAID 203 55NSAID 142 94Pairs, ratio of discordant pairs 2.58 [1.89, 3.52] truth 2.92 to 2.99Pairs, conditional logistic 2.58 [1.89, 3.52] truth 2.92 to 2.99McNemar chi-square 38.42, df 1, p = 5.7e-10Of the 494 pairs, 297 are concordant, 203 with neither person exposed and 94 with both, and they drop out. In the 197 discordant pairs the case alone used NSAIDs 142 times and the control alone 55 times, and 142 / 55 = 2.58, with an interval from 1.89 to 3.52. Conditional logistic regression on the same pairs returns the same estimate and the same limits. McNemar’s chi-square is (142 − 55)² / (142 + 55) = 38.42, with p = 5.7e-10. The interval from the pairs is wider than the interval from the full sets, 2.15 to 3.67, because the second control in each set adds information.
What matching does not do
Section titled “What matching does not do”Matching forces the cases and the controls to share one distribution of the matching factors. The code compares the age distribution of cases and controls in the matched sample, reads the odds ratio for age 70-79 from the model of the unmatched sample, and then asks the matched sample for the effect of age. The Python code counts the age bands within each matched set.
age_share <- prop.table(table(case = matched$case, age_band = matched$age_band), 1)print(round(age_share, 3))age_odds_ratio <- exp(coef(unmatched_fit)[["age_band70-79"]])cat(sprintf("Unmatched sample, age 70-79 against 40-49: %.2f, %s\n", age_odds_ratio, sprintf("truth %.2f to %.2f", min(true_age_or), max(true_age_or))))factor_fit <- clogit(case ~ nsaid + age_band + strata(set_id), data = matched)print(round(coef(factor_fit), 3)) age_bandcase 40-49 50-59 60-69 70-79 0 0.087 0.196 0.298 0.419 1 0.087 0.196 0.298 0.419Unmatched sample, age 70-79 against 40-49: 4.69, truth 3.86 to 3.96 nsaid age_band50-59 age_band60-69 age_band70-79 1.034 NA NA NAage_share = pd.crosstab(matched["case"], matched["age_band"], normalize="index")print(age_share.round(3))age_odds_ratio = np.exp(unmatched_fit.params["age_band[T.70-79]"])print(f"Unmatched sample, age 70-79 against 40-49: {age_odds_ratio:.2f}, " f"truth {true_age_or.min():.2f} to {true_age_or.max():.2f}")bands_per_set = matched.groupby("set_id")["age_band"].nunique()print(f"Largest number of age bands in one matched set: " f"{bands_per_set.max()}")age_band 40-49 50-59 60-69 70-79case0 0.087 0.196 0.298 0.4191 0.087 0.196 0.298 0.419Unmatched sample, age 70-79 against 40-49: 4.69, truth 3.86 to 3.96Largest number of age bands in one matched set: 1Cases and controls have identical age distributions, 8.7%, 19.6%, 29.8% and 41.9% across the four bands, so the matched sample holds no contrast in age between cases and controls. Every matched set lies within one age band, and the conditional likelihood compares people within a set, so R returns NA for the age band coefficients. The unmatched sample still estimates the effect of age, 4.69 for age 70-79 against 40-49, where the truth lies between 3.86 and 3.96. A matched design gives up the effect of each matching factor on the outcome. It can still estimate whether a matching factor modifies the effect of exposure, through a product term of exposure and that factor in the conditional model.
Overmatching
Section titled “Overmatching”Overmatching has two forms. Matching on a correlate of the exposure that is not a risk factor for the outcome makes cases and their controls more alike in exposure, so more sets are concordant, and when the analysis accounts for the matching it costs precision without bias. Matching on a variable that the exposure affects and that lies on the path to the outcome biases the estimate of the total effect, and the overmatched sample shows that form. In the simulation NSAID use raises the odds of an ulcer, and an ulcer raises the odds of a bleed. The sample matches on ulcer status as well as on age band and sex, so its conditional analysis estimates the odds ratio with ulcer status held fixed, which is 1.5 by construction.
ulcer_share <- tapply(overmatched$ulcer, overmatched$case, mean)cat(sprintf("Ulcer: %.3f of cases, %.3f of their controls\n", ulcer_share[["1"]], ulcer_share[["0"]]))cat(sprintf("NSAID use among controls: %.3f matched, %.3f overmatched\n", mean(matched$nsaid[matched$case == 0]), mean(overmatched$nsaid[overmatched$case == 0])))overmatched_fit <- clogit(case ~ nsaid + strata(set_id), data = overmatched)overmatched_row <- ModelOddsRatio(overmatched_fit, "Overmatched on ulcer, conditional")PrintRows(overmatched_row, "1.50")Ulcer: 0.609 of cases, 0.609 of their controlsNSAID use among controls: 0.291 matched, 0.389 overmatchedOvermatched on ulcer, conditional 1.63 [1.26, 2.10] truth 1.50ulcer_share = overmatched.groupby("case")["ulcer"].mean()print(f"Ulcer: {ulcer_share[1]:.3f} of cases, " f"{ulcer_share[0]:.3f} of their controls")overmatched_controls = overmatched.loc[overmatched["case"] == 0, "nsaid"]print(f"NSAID use among controls: {matched_controls:.3f} matched, " f"{overmatched_controls.mean():.3f} overmatched")overmatched_fit = ConditionalLogit( overmatched["case"], overmatched[["nsaid"]], groups=overmatched["set_id"]).fit()overmatched_row = model_odds_ratio(overmatched_fit, "Overmatched on ulcer, conditional")print_rows([overmatched_row], "1.50")Ulcer: 0.609 of cases, 0.609 of their controlsNSAID use among controls: 0.291 matched, 0.389 overmatchedOvermatched on ulcer, conditional 1.63 [1.26, 2.10] truth 1.50An ulcer occurred in 60.9% of the cases and, by design, in 60.9% of their controls. NSAID use among the controls rose from 29.1% to 38.9%, because NSAID users more often have an ulcer. Conditional logistic regression returns 1.63, with an interval from 1.26 to 2.10 that excludes the total effect of 2.92 to 2.99 and covers the 1.5 that holds with ulcer status fixed. The analysis compared people with the same ulcer status and so removed the part of the effect that runs through ulcers. A reader who wants to know how much NSAIDs raise the odds of a bleed gets 1.63 in place of about 3, and no analysis of this sample can recover the total, because the controls were chosen on the mediator. Match only on factors that precede the exposure, for the reasons the confounding page gives for adjustment.
Matching factors as covariates
Section titled “Matching factors as covariates”An unconditional logistic model can account for the matching by including the matching factors as covariates. The code fits it to the matched sample, sets it beside the conditional fit, and counts the strata that the two matching factors define.
covariate_fit <- glm(case ~ nsaid + age_band + sex, family = binomial, data = matched)covariate_rows <- rbind( ModelOddsRatio(conditional_fit, "Matched, conditional logistic"), ModelOddsRatio(covariate_fit, "Matched, age and sex as covariates"))PrintRows(covariate_rows, total_truth)cat(sprintf("Standard error of the log odds ratio: %.4f and %.4f\n", sqrt(vcov(conditional_fit)["nsaid", "nsaid"]), sqrt(vcov(covariate_fit)["nsaid", "nsaid"])))set_sizes <- table(matched$age_band[matched$case == 1], matched$sex[matched$case == 1])cat(sprintf("Matching strata: %d, with %d to %d cases each\n", length(set_sizes), min(set_sizes), max(set_sizes)))results <- rbind(results, covariate_rows[2, ], overmatched_row)Matched, conditional logistic 2.81 [2.15, 3.67] truth 2.92 to 2.99Matched, age and sex as covariates 2.93 [2.24, 3.82] truth 2.92 to 2.99Standard error of the log odds ratio: 0.1364 and 0.1361Matching strata: 8, with 12 to 110 cases eachcovariate_fit = smf.glm("case ~ nsaid + age_band + sex", data=matched, family=sm.families.Binomial()).fit()covariate_rows = [ model_odds_ratio(conditional_fit, "Matched, conditional logistic"), model_odds_ratio(covariate_fit, "Matched, age and sex as covariates"),]print_rows(covariate_rows, total_truth)print("Standard error of the log odds ratio: " f"{conditional_fit.bse['nsaid']:.4f} and " f"{covariate_fit.bse['nsaid']:.4f}")set_sizes = matched[matched["case"] == 1].groupby( ["age_band", "sex"]).size()print(f"Matching strata: {len(set_sizes)}, with {set_sizes.min()} to " f"{set_sizes.max()} cases each")results += [covariate_rows[1], overmatched_row]Matched, conditional logistic 2.81 [2.15, 3.67] truth 2.92 to 2.99Matched, age and sex as covariates 2.93 [2.24, 3.82] truth 2.92 to 2.99Standard error of the log odds ratio: 0.1364 and 0.1361Matching strata: 8, with 12 to 110 cases eachThe covariate model gives 2.93 (2.24 to 3.82) and the conditional model 2.81 (2.15 to 3.67), with standard errors of the log odds ratio of 0.1361 and 0.1364. The two agree closely because the matching was coarse. Four age bands and two sexes make 8 matching strata with 12 to 110 cases each, every matched set in a stratum shares its baseline odds, and age band and sex enter the model as additive terms, as they enter the simulation. That is when the broader analysis is acceptable: few coarse matching strata, many sets in each, and a model that includes every matching factor in a form that fits.
With fine matching, such as pairs matched on exact age, on neighborhood or on family, each set is its own stratum. An unconditional model with one indicator per set is then biased, and for 1:1 pairs it estimates the square of the odds ratio. Conditional logistic regression is the analysis for that design.
Every odds ratio beside the truth
Section titled “Every odds ratio beside the truth”The forest plot puts the seven odds ratios of the page on one log axis. A gray band marks the true total odds ratio, 2.92 to 2.99, and a dotted line marks 1.5, the truth with ulcer status fixed. The color marks how each analysis handled age and sex.
results$analysis <- factor(results$analysis, levels = rev(results$analysis))results$handling <- c("Ignores age and sex", "Accounts for age and sex", "Ignores age and sex", "Accounts for age and sex", "Accounts for age and sex", "Accounts for age and sex", "Matched on a mediator")forest_plot <- ggplot(results, aes(odds_ratio, analysis, color = handling)) + annotate("rect", xmin = min(true_or), xmax = max(true_or), ymin = -Inf, ymax = Inf, fill = "gray80") + geom_vline(xintercept = 1, color = "gray60") + geom_vline(xintercept = 1.5, linetype = "dotted", color = "gray40") + geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.25, orientation = "y") + geom_point(size = 3) + scale_x_log10(breaks = c(1, 1.5, 2, 3, 4, 6, 8), limits = c(0.9, 8), labels = c("1", "1.5", "2", "3", "4", "6", "8")) + scale_color_manual(values = c("Accounts for age and sex" = "#1f4e5f", "Ignores age and sex" = "#c44e52", "Matched on a mediator" = "#dd8452"), name = NULL) + labs(x = paste("Odds ratio (log scale)\nGray band: true total effect.", "Dotted line: truth with ulcer fixed."), y = NULL) + theme_classic(base_size = 12) + theme(legend.position = "bottom")ggsave("outputs/case-control-forest-r.png", forest_plot, width = 7.5, height = 4.4, dpi = 150)
forest = pd.DataFrame(results)forest["handling"] = ["Ignores age and sex", "Accounts for age and sex", "Ignores age and sex", "Accounts for age and sex", "Accounts for age and sex", "Accounts for age and sex", "Matched on a mediator"]forest["position"] = np.arange(len(forest))[::-1]colors = {"Accounts for age and sex": "#1f4e5f", "Ignores age and sex": "#c44e52", "Matched on a mediator": "#dd8452"}figure, axes = plt.subplots(figsize=(7.5, 4.4))axes.axvspan(true_or.min(), true_or.max(), color="0.8")axes.axvline(1, color="0.6")axes.axvline(1.5, color="0.4", linestyle=":")for handling, color in colors.items(): rows = forest[forest["handling"] == handling] estimate = rows["odds_ratio"].to_numpy() axes.errorbar(estimate, rows["position"].to_numpy(), xerr=[estimate - rows["lower"].to_numpy(), rows["upper"].to_numpy() - estimate], fmt="o", color=color, capsize=4, label=handling)axes.set_xscale("log")axes.set_xlim(0.9, 8)axes.set_xticks([1, 1.5, 2, 3, 4, 6, 8], labels=["1", "1.5", "2", "3", "4", "6", "8"])axes.set_xticks([], minor=True)axes.set_yticks(forest["position"], labels=forest["analysis"])axes.set_xlabel("Odds ratio (log scale)\nGray band: true total effect. " "Dotted line: truth with ulcer fixed.")axes.legend(loc="upper center", bbox_to_anchor=(0.3, -0.28), ncol=3, frameon=False, fontsize=9)figure.tight_layout()figure.savefig(output / "case-control-forest-python.png", dpi=150)plt.close(figure)
The two estimates that ignore age and sex fall on either side of the truth, 5.07 with random controls and 2.22 with matched controls, and neither interval reaches the gray band. The four analyses that account for age and sex lie between 2.58 and 3.46, and each interval covers the band. The overmatched estimate, 1.63, lies near the dotted line at 1.5, the truth for the question that design answers.
Mistakes to avoid
Section titled “Mistakes to avoid”Do not choose controls from a group whose exposure does not represent the source population. Hospital controls admitted for arthritis or back pain use NSAIDs more often than the cohort they stand for. The matched sample showed what such a shift does: controls with 29.1% NSAID use in place of 15.3% moved the crude odds ratio from 5.07 to 2.22. There the cause was age, which the conditional analysis removed. When the cause is the reason the controls were admitted, no column of the data records it, and the bias analysis page corrects the estimate with assumed selection probabilities.
Do not read the odds ratio as a risk ratio unless the outcome is rare in the source population. Here 494 of 120,000 people bled within five years, about 0.4%, so the odds ratio of about 3 is close to the risk ratio. With a common outcome the two measures separate, as the risk measures page shows. The study designs page shows how the way the controls are sampled decides which ratio the odds ratio estimates.
Do not report a risk from a case-control sample. The intercept of the adjusted model read as 8.5% for a group whose true risk is 0.100%.
Do not analyze a matched sample as if it were unmatched. Ignoring the sets gave 2.22, and conditioning on them gave 2.81.
Do not match on a consequence of the exposure. Matching on ulcer status gave 1.63 where the total effect is 2.92 to 2.99.
Scientific references
Section titled “Scientific references”The survival package by Therneau supplies the Kaplan-Meier, Cox, and parametric survival models in R.
Breslow and colleagues, 1978 describe the estimation of multiple relative risk functions in matched case-control studies.
McNemar, 1947 presents formulas for judging the significance of the difference between correlated proportions and points out the chi-square equivalent of one of them.
Further reading
Section titled “Further reading”The R documentation of clogit() describes the strata() term that names the matched set and the exact and approximate methods for the conditional likelihood.
The statsmodels documentation of ConditionalLogit explains that each group has an implicit intercept that the conditional likelihood removes. The documentation of mcnemar() covers the exact binomial version of the test and the continuity correction.
The logistic regression page explains the odds ratio of a logistic model, and the categorical data page covers the chi-square and Fisher tests for the 2x2 table that starts this page.