Study Designs & Measures of Occurrence
Prevalence, cumulative incidence and the incidence rate answer three different questions about how often a disease occurs. Each study design can estimate some of them and not the others. This page follows one simulated population of 6,000 adults for ten years, computes the three measures with their intervals, and then draws a cohort study, two case-control studies and a cross-sectional survey from the same people, so that every estimate can be set against a known truth.
Get the data
Section titled “Get the data”Download copd_population.csv into your working directory. The invented table has 6,000 rows, one per person, and six columns. smoker is 1 for a current smoker at enrollment. years_to_copd is the time from enrollment to a diagnosis of chronic obstructive pulmonary disease (COPD), and it is empty when no diagnosis was seen. years_observed is the time until the person left observation, and exit_reason says how: end for the end of the study at 10 years, lost for loss to follow-up, died for death. person_id and lottery complete the table. Everyone was free of COPD at enrollment, and the person is the unit of analysis.
lottery is a random permutation of the numbers 1 to 6,000. The page uses it wherever a study needs a random sample, so that R and Python select the same people. In your own work, call sample() or a NumPy generator.
The values come from a simulation in which every rate is constant over time. A non-smoker is diagnosed at 10 per 1,000 person-years, and smoking multiplies that rate by 2.5. After the diagnosis a non-smoker dies at 0.04 per year and a smoker at 0.12 per year, so COPD lasts a shorter time in smokers. Nobody dies without COPD, which keeps the accounting short. Everyone is lost to follow-up at 0.03 per year, whatever the smoking status or the disease status.
These rates fix every quantity that a study of this population can estimate. The 10-year risk of a diagnosis is 1 − exp(−10 × rate). The prevalence among those alive at year 10 needs the death rate as well: the code computes the probability of being diagnosed and still alive, and divides it by that probability plus the probability of no diagnosis. The code adds two columns to the table: copd marks a diagnosis, and years_at_risk is the time each person spent under observation and free of COPD.
library(epitools)library(survival)library(ggplot2)
population <- read.csv("copd_population.csv")dir.create("outputs", showWarnings = FALSE)population$copd <- as.integer(!is.na(population$years_to_copd))population$years_at_risk <- ifelse(population$copd == 1, population$years_to_copd, population$years_observed)groups <- c("Non-smokers", "Smokers")exits <- table(population$exit_reason)cat(sprintf("At year 10: %d, lost: %d, died: %d\n", exits[["end"]], exits[["lost"]], exits[["died"]]))cat(sprintf("Smokers %d of %d; diagnosed: %d non-smokers, %d smokers\n", sum(population$smoker), nrow(population), sum(population$copd[population$smoker == 0]), sum(population$copd[population$smoker == 1])))
rate <- c(0.010, 0.025)death_rate <- c(0.04, 0.12)true_risk <- 1 - exp(-10 * rate)living_cases <- rate / (death_rate - rate) * (exp(-10 * rate) - exp(-10 * death_rate))true_prevalence <- living_cases / (living_cases + exp(-10 * rate))truth <- rbind("Rate per 1,000 person-years" = 1000 * rate, "10-year risk" = true_risk, "Odds of the 10-year risk" = true_risk / (1 - true_risk), "Prevalence at year 10" = true_prevalence)truth <- cbind(truth, truth[, 2] / truth[, 1])colnames(truth) <- c(groups, "Ratio")print(round(truth, 4))At year 10: 4300, lost: 1507, died: 193Smokers 1822 of 6000; diagnosed: 338 non-smokers, 348 smokers Non-smokers Smokers RatioRate per 1,000 person-years 10.0000 25.0000 2.500010-year risk 0.0952 0.2212 2.3244Odds of the 10-year risk 0.1052 0.2840 2.7006Prevalence at year 10 0.0795 0.1390 1.7474from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom lifelines import KaplanMeierFitterfrom scipy import statsfrom statsmodels.discrete.conditional_models import ConditionalLogitfrom statsmodels.stats.contingency_tables import Table2x2from statsmodels.stats.proportion import proportion_confintfrom statsmodels.stats.rates import confint_poissonfrom statsmodels.stats.rates import confint_poisson_2indep
population = pd.read_csv("copd_population.csv")output = Path("outputs")output.mkdir(exist_ok=True)population["copd"] = population["years_to_copd"].notna().astype(int)population["years_at_risk"] = population["years_to_copd"].fillna( population["years_observed"])groups = ["Non-smokers", "Smokers"]exits = population["exit_reason"].value_counts()diagnosed = population.groupby("smoker")["copd"].sum()print(f"At year 10: {exits['end']}, lost: {exits['lost']}, " f"died: {exits['died']}")print(f"Smokers {population['smoker'].sum()} of {len(population)}; " f"diagnosed: {diagnosed[0]} non-smokers, {diagnosed[1]} smokers")
rate = np.array([0.010, 0.025])death_rate = np.array([0.04, 0.12])true_risk = 1 - np.exp(-10 * rate)living_cases = (rate / (death_rate - rate) * (np.exp(-10 * rate) - np.exp(-10 * death_rate)))true_prevalence = living_cases / (living_cases + np.exp(-10 * rate))truth = pd.DataFrame( [1000 * rate, true_risk, true_risk / (1 - true_risk), true_prevalence], columns=groups, index=["Rate per 1,000 person-years", "10-year risk", "Odds of the 10-year risk", "Prevalence at year 10"])truth["Ratio"] = truth["Smokers"] / truth["Non-smokers"]print(truth.round(4))At year 10: 4300, lost: 1507, died: 193Smokers 1822 of 6000; diagnosed: 338 non-smokers, 348 smokers Non-smokers Smokers RatioRate per 1,000 person-years 10.0000 25.0000 2.500010-year risk 0.0952 0.2212 2.3244Odds of the 10-year risk 0.1052 0.2840 2.7006Prevalence at year 10 0.0795 0.1390 1.7474Of the 6,000 people, 1,822 smoke. By year 10, 1,507 had been lost and 193 had died, and 4,300 were still under observation. Loading survival after epitools prints a note that ratetable is masked, and this page uses neither version of that function.
One exposure in one population has four true ratios. The rate ratio is 2.50, the ratio of the 10-year risks is 2.32, the ratio of the odds of those risks is 2.70, and the prevalence ratio at year 10 is 1.75. Each belongs to a measure of occurrence, and the rest of the page shows which design delivers which. The risk ratio is below the rate ratio because a risk has a ceiling at 1 and the smokers are closer to it; the risk measures page shows that effect and gives the interval formulas for each ratio.
Smoking was assigned at random in this simulation, so each ratio also measures what smoking causes. In a real population smokers differ from non-smokers in age, occupation and much else, and a ratio then needs the adjustment that the confounding and DAGs page describes.
Three measures of occurrence
Section titled “Three measures of occurrence”The incidence rate divides the new cases by the person-time at risk. A person stops adding person-time at the diagnosis, at loss to follow-up, at death or at the end of the study, whichever comes first. Time lived after the diagnosis is not time at risk of a first diagnosis, so it stays out of the denominator. The interval is the exact Poisson interval, from poisson.test() in R and from confint_poisson() with method="exact-c" in statsmodels. The code also prints the shortcut that divides the cases by the people times 10 years.
Cumulative incidence, or risk, is the probability of a diagnosis within 10 years for a person who starts free of COPD. Cases divided by people estimate it only when everyone is followed for the whole period, and here 1,507 people were lost. The Kaplan-Meier method repairs this when loss is unrelated to the disease, as it is here by construction: at each diagnosis time it multiplies the probability of staying free by the share of the people still at risk who were not diagnosed. The function below also returns the Greenwood standard error. survfit() and lifelines confirm it and give an interval on the log(−log) scale, and the Kaplan-Meier page covers the assumptions. With a constant rate the risk is also 1 − exp(−10 × rate).
Point prevalence is the share of a population that has the disease at one moment. At year 10 the population is the 4,300 people still under observation. The interval of a proportion is the Wilson score interval, from prop.test() without continuity correction in R and from proportion_confint() with method="wilson" in Python.
#' Estimate a risk at a time horizon with the Kaplan-Meier method.#'#' @param time Years at risk for each person.#' @param event 1 for a diagnosis at that time, 0 for a censored time.#' @param horizon The time at which the risk is evaluated.#' @return A named vector with the risk and its Greenwood standard error.KaplanMeierRisk <- function(time, event, horizon) { survival <- 1 greenwood <- 0 for (event_time in sort(unique(time[event == 1 & time <= horizon]))) { at_risk <- sum(time >= event_time) diagnosed <- sum(time == event_time & event == 1) survival <- survival * (1 - diagnosed / at_risk) greenwood <- greenwood + diagnosed / (at_risk * (at_risk - diagnosed)) } c(risk = 1 - survival, se = survival * sqrt(greenwood))}
present <- population[population$exit_reason == "end", ]for (group in 0:1) { rows <- population[population$smoker == group, ] now <- present[present$smoker == group, ] cases <- sum(rows$copd) person_years <- sum(rows$years_at_risk) exact <- 1000 * poisson.test(cases, person_years)$conf.int simple <- prop.test(cases, nrow(rows), correct = FALSE) by_hand <- KaplanMeierRisk(rows$years_at_risk, rows$copd, 10) at_ten <- summary(survfit(Surv(years_at_risk, copd) ~ 1, data = rows, conf.type = "log-log"), times = 10) wilson <- prop.test(sum(now$copd), nrow(now), correct = FALSE) case_exits <- table(factor(rows$exit_reason[rows$copd == 1], levels = c("end", "died", "lost"))) cat(sprintf("%s: %d people, %d cases, %d present at year 10\n", groups[group + 1], nrow(rows), cases, nrow(now))) cat(sprintf(" rate %d / %.0f person-years = %.2f per 1,000", cases, person_years, 1000 * cases / person_years)) cat(sprintf(" [%.2f, %.2f]\n", exact[1], exact[2])) cat(sprintf(" shortcut %d / (%d x 10 years) = %.2f per 1,000\n", cases, nrow(rows), 1000 * cases / (10 * nrow(rows)))) cat(sprintf(" risk true %.4f; cases / people %.4f [%.4f, %.4f]\n", true_risk[group + 1], simple$estimate, simple$conf.int[1], simple$conf.int[2])) cat(sprintf(" Kaplan-Meier %.4f [%.4f, %.4f]; from rate %.4f\n", 1 - at_ten$surv, 1 - at_ten$upper, 1 - at_ten$lower, 1 - exp(-10 * cases / person_years))) cat(sprintf(" by hand %.4f, se %.4f; survfit se %.4f\n", by_hand[["risk"]], by_hand[["se"]], at_ten$std.err)) cat(sprintf(" prevalence %d / %d = %.4f [%.4f, %.4f]\n", sum(now$copd), nrow(now), wilson$estimate, wilson$conf.int[1], wilson$conf.int[2])) cat(sprintf(" of %d cases: %d present, %d died, %d lost; ", cases, case_exits[["end"]], case_exits[["died"]], case_exits[["lost"]])) cat(sprintf("%.0f years lived with COPD\n", sum(rows$years_observed - rows$years_at_risk)))}Non-smokers: 4178 people, 338 cases, 3049 present at year 10 rate 338 / 34639 person-years = 9.76 per 1,000 [8.75, 10.86] shortcut 338 / (4178 x 10 years) = 8.09 per 1,000 risk true 0.0952; cases / people 0.0809 [0.0730, 0.0896] Kaplan-Meier 0.0937 [0.0846, 0.1037]; from rate 0.0930 by hand 0.0937, se 0.0049; survfit se 0.0049 prevalence 250 / 3049 = 0.0820 [0.0728, 0.0923] of 338 cases: 250 present, 44 died, 44 lost; 1406 years lived with COPDSmokers: 1822 people, 348 cases, 1251 present at year 10 rate 348 / 14198 person-years = 24.51 per 1,000 [22.00, 27.23] shortcut 348 / (1822 x 10 years) = 19.10 per 1,000 risk true 0.2212; cases / people 0.1910 [0.1736, 0.2097] Kaplan-Meier 0.2180 [0.1984, 0.2392]; from rate 0.2174 by hand 0.2180, se 0.0104; survfit se 0.0104 prevalence 173 / 1251 = 0.1383 [0.1203, 0.1585] of 348 cases: 173 present, 149 died, 26 lost; 1186 years lived with COPDdef kaplan_meier_risk(time, event, horizon): """Estimate a risk at a time horizon with the Kaplan-Meier method.
Args: time: Years at risk for each person, as a numpy array. event: 1 for a diagnosis at that time, 0 for a censored time. horizon: The time at which the risk is evaluated.
Returns: A dictionary with the risk and its Greenwood standard error. """ survival = 1.0 greenwood = 0.0 for event_time in np.unique(time[(event == 1) & (time <= horizon)]): at_risk = (time >= event_time).sum() diagnosed = ((time == event_time) & (event == 1)).sum() survival *= 1 - diagnosed / at_risk greenwood += diagnosed / (at_risk * (at_risk - diagnosed)) return {"risk": 1 - survival, "se": survival * np.sqrt(greenwood)}
present = population[population["exit_reason"] == "end"]for group, label in enumerate(groups): rows = population[population["smoker"] == group] now = present[present["smoker"] == group] cases = rows["copd"].sum() person_years = rows["years_at_risk"].sum() exact = confint_poisson(cases, person_years, method="exact-c") simple = proportion_confint(cases, len(rows), method="wilson") by_hand = kaplan_meier_risk(rows["years_at_risk"].to_numpy(), rows["copd"].to_numpy(), 10) fitter = KaplanMeierFitter().fit(rows["years_at_risk"], rows["copd"]) limits = 1 - fitter.confidence_interval_survival_function_.iloc[-1] wilson = proportion_confint(now["copd"].sum(), len(now), method="wilson") case_exits = rows.loc[rows["copd"] == 1, "exit_reason"].value_counts() print(f"{label}: {len(rows)} people, {cases} cases, {len(now)} present " f"at year 10") print(f" rate {cases} / {person_years:.0f} person-years = " f"{1000 * cases / person_years:.2f} per 1,000 " f"[{1000 * exact[0]:.2f}, {1000 * exact[1]:.2f}]") print(f" shortcut {cases} / ({len(rows)} x 10 years) = " f"{1000 * cases / (10 * len(rows)):.2f} per 1,000") print(f" risk true {true_risk[group]:.4f}; cases / people " f"{cases / len(rows):.4f} [{simple[0]:.4f}, {simple[1]:.4f}]") print(f" Kaplan-Meier {1 - fitter.predict(10):.4f} " f"[{limits.iloc[1]:.4f}, {limits.iloc[0]:.4f}]; from rate " f"{1 - np.exp(-10 * cases / person_years):.4f}") print(f" by hand {by_hand['risk']:.4f}, " f"se {by_hand['se']:.4f}") print(f" prevalence {now['copd'].sum()} / {len(now)} = " f"{now['copd'].mean():.4f} [{wilson[0]:.4f}, {wilson[1]:.4f}]") print(f" of {cases} cases: {case_exits['end']} present, " f"{case_exits['died']} died, {case_exits['lost']} lost; " f"{(rows['years_observed'] - rows['years_at_risk']).sum():.0f} " f"years lived with COPD")Non-smokers: 4178 people, 338 cases, 3049 present at year 10 rate 338 / 34639 person-years = 9.76 per 1,000 [8.75, 10.86] shortcut 338 / (4178 x 10 years) = 8.09 per 1,000 risk true 0.0952; cases / people 0.0809 [0.0730, 0.0896] Kaplan-Meier 0.0937 [0.0846, 0.1037]; from rate 0.0930 by hand 0.0937, se 0.0049 prevalence 250 / 3049 = 0.0820 [0.0728, 0.0923] of 338 cases: 250 present, 44 died, 44 lost; 1406 years lived with COPDSmokers: 1822 people, 348 cases, 1251 present at year 10 rate 348 / 14198 person-years = 24.51 per 1,000 [22.00, 27.23] shortcut 348 / (1822 x 10 years) = 19.10 per 1,000 risk true 0.2212; cases / people 0.1910 [0.1736, 0.2097] Kaplan-Meier 0.2180 [0.1984, 0.2392]; from rate 0.2174 by hand 0.2180, se 0.0104 prevalence 173 / 1251 = 0.1383 [0.1203, 0.1585] of 348 cases: 173 present, 149 died, 26 lost; 1186 years lived with COPDThe rate is 9.76 per 1,000 person-years in non-smokers, with an interval from 8.75 to 10.86, and 24.51 in smokers, with an interval from 22.00 to 27.23. Both intervals contain the true rates of 10 and 25. The shortcut gives 8.09 and 19.10, which is 17% and 22% too low, because 4,178 non-smokers did not supply 41,780 years at risk. They supplied 34,639; the rest was never observed or was lived after the diagnosis. Smokers leave the risk set sooner, so the shortcut also distorts the comparison between the groups.
Cases over people give non-smokers a 10-year risk of 0.0809 with a Wilson interval from 0.0730 to 0.0896, and the true risk of 0.0952 lies above it. For smokers they give 0.1910 with an interval from 0.1736 to 0.2097, against a truth of 0.2212. Both intervals are narrow and both miss, because an interval measures sampling error and loss to follow-up is a bias. The Kaplan-Meier risks are 0.0937 and 0.2180, and their intervals contain the truth. The hand calculation matches survfit() in the risk and the standard error, and lifelines prints the same risk and limits.
The rate gives a third route to the risk, 0.0930 and 0.2174, because person-time takes each person for as long as that person was observed. Use that conversion only when a constant rate is plausible for the disease and the period.
The prevalence at year 10 is 0.0820 in non-smokers and 0.1383 in smokers, and both intervals contain the truth. Smokers now carry three numbers: a rate of 24.51 per 1,000 person-years, a 10-year risk of 0.2180 and a prevalence of 0.1383. The rate has a time unit, the risk belongs to a period, and the prevalence belongs to a date. The prevalence is the lowest because it counts only the cases who are still there: of the 348 smokers with a diagnosis, 149 had died by year 10, against 44 of the 338 non-smokers.
Draw the person-time
Section titled “Draw the person-time”A plot of follow-up lines shows what the denominator of a rate is made of. DrawSample() sorts the candidates by their lottery number plus a shift, modulo 6,000, and keeps the first ones. The lottery numbers are in random order, so that is a simple random sample, and a different shift gives a different sample. The code draws 30 people from each group.
#' Draw a random sample of rows with the lottery numbers.#'#' @param pool A data frame with the column lottery.#' @param size The number of rows to draw.#' @param shift A whole number. Each value gives a different sample.#' @return The drawn rows of pool.DrawSample <- function(pool, size, shift) { key <- (pool$lottery + shift) %% 6000 pool[order(key)[seq_len(size)], ]}
shown <- rbind(DrawSample(population[population$smoker == 0, ], 30, 1000), DrawSample(population[population$smoker == 1, ], 30, 1000))shown <- shown[order(shown$smoker, shown$years_observed, shown$years_at_risk), ]shown$row <- ave(seq_len(nrow(shown)), shown$smoker, FUN = seq_along)shown$group <- groups[shown$smoker + 1]shown$exit <- c(end = "Present at year 10", lost = "Lost to follow-up", died = "Died")[shown$exit_reason]timeline <- ggplot(shown, aes(y = row)) + geom_segment(aes(x = 0, xend = years_at_risk, yend = row, color = "At risk"), linewidth = 1) + geom_segment(aes(x = years_at_risk, xend = years_observed, yend = row, color = "Living with COPD"), linewidth = 1) + geom_point(aes(x = years_observed, shape = exit), size = 1.8) + facet_wrap(~group) + scale_color_manual(values = c("At risk" = "#4c72b0", "Living with COPD" = "#c44e52")) + scale_shape_manual(values = c("Present at year 10" = 16, "Lost to follow-up" = 4, "Died" = 17)) + scale_x_continuous(breaks = seq(0, 10, 2)) + guides(color = guide_legend(order = 1), shape = guide_legend(order = 2)) + labs(x = "Years since enrollment", y = "30 people from each group", color = NULL, shape = NULL) + theme_classic(base_size = 11) + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), legend.position = "bottom", legend.box = "vertical")ggsave("outputs/person-time-r.png", timeline, width = 7, height = 5, dpi = 150)
def draw_sample(pool, size, shift): """Draw a random sample of rows with the lottery numbers.
Args: pool: A data frame with the column lottery. size: The number of rows to draw. shift: A whole number. Each value gives a different sample.
Returns: The drawn rows of pool. """ key = (pool["lottery"] + shift) % 6000 return pool.loc[key.sort_values().index[:size]]
exit_markers = [("end", "o", "Present at year 10"), ("lost", "x", "Lost to follow-up"), ("died", "^", "Died")]figure, panels = plt.subplots(1, 2, figsize=(7, 5), sharey=True)for group, panel in enumerate(panels): rows = draw_sample(population[population["smoker"] == group], 30, 1000) rows = rows.sort_values(["years_observed", "years_at_risk"]) position = np.arange(len(rows)) panel.hlines(position, 0, rows["years_at_risk"], color="#4c72b0", linewidth=1.5, label="At risk") panel.hlines(position, rows["years_at_risk"], rows["years_observed"], color="#c44e52", linewidth=1.5, label="Living with COPD") for reason, marker, label in exit_markers: ends = (rows["exit_reason"] == reason).to_numpy() panel.scatter(rows["years_observed"].to_numpy()[ends], position[ends], color="black", marker=marker, s=16, label=label) panel.set(title=groups[group], xlabel="Years since enrollment", xticks=range(0, 11, 2), yticks=[])panels[0].set_ylabel("30 people from each group")handles, labels = panels[1].get_legend_handles_labels()figure.legend(handles, labels, loc="lower center", ncol=3, frameon=False)figure.tight_layout(rect=(0, 0.1, 1, 1))figure.savefig(output / "person-time-python.png", dpi=150)plt.close(figure)
The blue length is the person-time at risk, the denominator of the incidence rate. The red length is time lived with COPD: it feeds the prevalence and stays out of the rate. A line that stops at a cross before year 10 is a person whom cases over people treat as never diagnosed. A red line that ends in a triangle is a case that a survey at year 10 cannot find.
A cohort study
Section titled “A cohort study”A cohort study enrolls people who are free of the disease, records the exposure, and follows them for new cases. It observes person-time and events in each exposure group, so it can estimate both rates and risks. Draw 2,400 people at enrollment. The rate ratio takes the Wald interval on the log scale, from rateratio() in epitools and from confint_poisson_2indep() with method="wald-log" in statsmodels. The risk ratio compares the two Kaplan-Meier risks at 10 years; the standard error of each log risk is its Greenwood standard error divided by the risk, and the two squared terms add.
cohort <- DrawSample(population, 2400, 0)smokers <- cohort[cohort$smoker == 1, ]others <- cohort[cohort$smoker == 0, ]cohort_counts <- c(sum(others$copd), sum(smokers$copd), sum(others$years_at_risk), sum(smokers$years_at_risk))rate_ratio <- rateratio(cohort_counts, method = "wald")$measure[2, ]risk_1 <- KaplanMeierRisk(smokers$years_at_risk, smokers$copd, 10)risk_0 <- KaplanMeierRisk(others$years_at_risk, others$copd, 10)se_log_rr <- sqrt((risk_1[["se"]] / risk_1[["risk"]])^2 + (risk_0[["se"]] / risk_0[["risk"]])^2)risk_ratio <- exp(log(risk_1[["risk"]] / risk_0[["risk"]]) + c(0, -1, 1) * qnorm(0.975) * se_log_rr)cat(sprintf("%-11s %4d people, %3d cases, %5.0f person-years\n", groups, c(nrow(others), nrow(smokers)), cohort_counts[1:2], cohort_counts[3:4]), sep = "")cat(sprintf("Rate ratio %.2f, 95%% CI [%.2f, %.2f]\n", rate_ratio[1], rate_ratio[2], rate_ratio[3]))cat(sprintf("10-year risks %.4f and %.4f, difference %.4f\n", risk_0[["risk"]], risk_1[["risk"]], risk_1[["risk"]] - risk_0[["risk"]]))cat(sprintf("Risk ratio %.2f, 95%% CI [%.2f, %.2f]\n", risk_ratio[1], risk_ratio[2], risk_ratio[3]))Non-smokers 1688 people, 138 cases, 14033 person-yearsSmokers 712 people, 141 cases, 5528 person-yearsRate ratio 2.59, 95% CI [2.05, 3.28]10-year risks 0.0950 and 0.2239, difference 0.1289Risk ratio 2.36, 95% CI [1.90, 2.93]cohort = draw_sample(population, 2400, 0)smokers = cohort[cohort["smoker"] == 1]others = cohort[cohort["smoker"] == 0]counts = [smokers["copd"].sum(), smokers["years_at_risk"].sum(), others["copd"].sum(), others["years_at_risk"].sum()]rate_ratio = [(counts[0] / counts[1]) / (counts[2] / counts[3]), *confint_poisson_2indep(*counts, method="wald-log", compare="ratio")]risk_1 = kaplan_meier_risk(smokers["years_at_risk"].to_numpy(), smokers["copd"].to_numpy(), 10)risk_0 = kaplan_meier_risk(others["years_at_risk"].to_numpy(), others["copd"].to_numpy(), 10)se_log_rr = np.sqrt((risk_1["se"] / risk_1["risk"]) ** 2 + (risk_0["se"] / risk_0["risk"]) ** 2)risk_ratio = np.exp(np.log(risk_1["risk"] / risk_0["risk"]) + np.array([0, -1, 1]) * stats.norm.ppf(0.975) * se_log_rr)for label, rows in zip(groups, (others, smokers)): print(f"{label:<11} {len(rows):4d} people, {rows['copd'].sum():3d} " f"cases, {rows['years_at_risk'].sum():5.0f} person-years")print(f"Rate ratio {rate_ratio[0]:.2f}, 95% CI [{rate_ratio[1]:.2f}, " f"{rate_ratio[2]:.2f}]")print(f"10-year risks {risk_0['risk']:.4f} and {risk_1['risk']:.4f}, " f"difference {risk_1['risk'] - risk_0['risk']:.4f}")print(f"Risk ratio {risk_ratio[0]:.2f}, 95% CI [{risk_ratio[1]:.2f}, " f"{risk_ratio[2]:.2f}]")Non-smokers 1688 people, 138 cases, 14033 person-yearsSmokers 712 people, 141 cases, 5528 person-yearsRate ratio 2.59, 95% CI [2.05, 3.28]10-year risks 0.0950 and 0.2239, difference 0.1289Risk ratio 2.36, 95% CI [1.90, 2.93]The cohort holds 1,688 non-smokers and 712 smokers, with 138 and 141 diagnoses. The rate ratio is 2.59 with an interval from 2.05 to 3.28, around the true 2.50. The risk ratio is 2.36 with an interval from 1.90 to 2.93, around the true 2.32. The same cohort gives the absolute measure: the 10-year risks are 0.0950 and 0.2239, a difference of 0.1289, or about 13 extra diagnoses per 100 smokers in 10 years. Both ratios are valid estimates of different quantities, so state which one you report and, for the risk ratio, the period it covers.
A case-control study, with controls sampled two ways
Section titled “A case-control study, with controls sampled two ways”A case-control study starts from the cases and adds a sample of people without the disease, the controls, to learn how common the exposure is in the population that produced the cases. Only the cases and a few controls per case need the exposure measured, which makes it the efficient design when that measurement is expensive. It observes no person-time and no risks. Its one measure is the odds ratio, and what that odds ratio estimates depends on where the controls come from. Both designs below take all 686 cases and two controls per case.
The first design samples the controls at the end of the study from the people who are still present and free of COPD. Its target is the ratio of the expected numbers of observed cases per survivor in the two groups. In each group that number is λ / (λ + 0.03) × (exp(10 × (λ + 0.03)) − 1) for a diagnosis rate λ and a loss rate of 0.03 per year. Without loss it would be the ratio of the odds of the 10-year risks.
The second design samples the controls while the cases occur. Each time a person is diagnosed, two controls are drawn from the people still at risk at that moment. This is incidence density sampling, also called risk-set sampling. A control drawn this way may be diagnosed later, and one person may serve as a control for more than one case. The sets are matched on time, so the analysis is a conditional logistic regression with one stratum per case, clogit() in survival and ConditionalLogit in statsmodels. The case-control page covers matched designs and that model.
#' Sample controls from the people at risk when each case is diagnosed.#'#' @param population A data frame with the columns person_id, smoker, copd,#' years_at_risk and lottery.#' @param per_case The number of controls for each case.#' @return One row per member of a matched set, with the columns set, case,#' smoker and person_id.DensitySample <- function(population, per_case) { cases <- population[population$copd == 1, ] sets <- vector("list", nrow(cases)) for (i in seq_len(nrow(cases))) { at_risk <- population[population$years_at_risk > cases$years_at_risk[i], ] controls <- DrawSample(at_risk, per_case, cases$lottery[i]) sets[[i]] <- data.frame( set = i, case = c(1, rep(0, per_case)), smoker = c(cases$smoker[i], controls$smoker), person_id = c(cases$person_id[i], controls$person_id) ) } do.call(rbind, sets)}
cases <- population[population$copd == 1, ]survivors <- present[present$copd == 0, ]survivor_controls <- DrawSample(survivors, 2 * nrow(cases), 4000)survivor_table <- table( smoker = c(cases$smoker, survivor_controls$smoker), case = rep(1:0, c(nrow(cases), nrow(survivor_controls))))survivor_or <- oddsratio(survivor_table, method = "wald")$measure[2, ]seen_per_survivor <- rate / (rate + 0.03) * (exp(10 * (rate + 0.03)) - 1)survivor_target <- seen_per_survivor[2] / seen_per_survivor[1]cat(sprintf("Smokers: %d of %d cases, %d of %d survivor controls\n", sum(cases$smoker), nrow(cases), sum(survivor_controls$smoker), nrow(survivor_controls)))cat(sprintf("Share of smokers: %.3f at enrollment, %.3f of %d survivors\n", mean(population$smoker), mean(survivors$smoker), nrow(survivors)))cat(sprintf("Survivor controls: odds ratio %.2f [%.2f, %.2f], target %.2f\n", survivor_or[1], survivor_or[2], survivor_or[3], survivor_target))
matched <- DensitySample(population, 2)density_controls <- matched[matched$case == 0, ]conditional_fit <- clogit(case ~ smoker + strata(set), data = matched)density_or <- exp(c(coef(conditional_fit), confint(conditional_fit)))cat(sprintf("%d control picks of %d people, %d picks diagnosed later\n", nrow(density_controls), length(unique(density_controls$person_id)), sum(density_controls$person_id %in% cases$person_id)))cat(sprintf("Share of smokers: %.3f of picks, %.3f of person-years\n", mean(density_controls$smoker), sum(population$years_at_risk[population$smoker == 1]) / sum(population$years_at_risk)))cat(sprintf("Density controls: odds ratio %.2f [%.2f, %.2f], target %.2f\n", density_or[1], density_or[2], density_or[3], truth[1, 3]))Smokers: 348 of 686 cases, 380 of 1372 survivor controlsShare of smokers: 0.304 at enrollment, 0.278 of 3877 survivorsSurvivor controls: odds ratio 2.69 [2.22, 3.25], target 2.711372 control picks of 1248 people, 80 picks diagnosed laterShare of smokers: 0.299 of picks, 0.291 of person-yearsDensity controls: odds ratio 2.48 [2.03, 3.02], target 2.50def density_sample(population, per_case): """Sample controls from the people at risk when each case is diagnosed.
Args: population: A data frame with the columns person_id, smoker, copd, years_at_risk and lottery. per_case: The number of controls for each case.
Returns: One row per member of a matched set, with the columns set, case, smoker and person_id. """ sets = [] case_rows = population[population["copd"] == 1] for number, case in enumerate(case_rows.itertuples(), start=1): at_risk = population[ population["years_at_risk"] > case.years_at_risk] controls = draw_sample(at_risk, per_case, case.lottery) sets.append(pd.DataFrame({ "set": number, "case": [1] + [0] * per_case, "smoker": [case.smoker, *controls["smoker"]], "person_id": [case.person_id, *controls["person_id"]]})) return pd.concat(sets, ignore_index=True)
cases = population[population["copd"] == 1]survivors = present[present["copd"] == 0]survivor_controls = draw_sample(survivors, 2 * len(cases), 4000)case_smokers = cases["smoker"].sum()control_smokers = survivor_controls["smoker"].sum()survivor_2x2 = Table2x2(np.array( [[case_smokers, control_smokers], [len(cases) - case_smokers, len(survivor_controls) - control_smokers]]))survivor_or = [survivor_2x2.oddsratio, *survivor_2x2.oddsratio_confint()]seen_per_survivor = (rate / (rate + 0.03) * (np.exp(10 * (rate + 0.03)) - 1))survivor_target = seen_per_survivor[1] / seen_per_survivor[0]print(f"Smokers: {case_smokers} of {len(cases)} cases, {control_smokers} " f"of {len(survivor_controls)} survivor controls")print(f"Share of smokers: {population['smoker'].mean():.3f} at " f"enrollment, {survivors['smoker'].mean():.3f} of {len(survivors)} " f"survivors")print(f"Survivor controls: odds ratio {survivor_or[0]:.2f} " f"[{survivor_or[1]:.2f}, {survivor_or[2]:.2f}], target " f"{survivor_target:.2f}")
matched = density_sample(population, 2)density_controls = matched[matched["case"] == 0]conditional_fit = ConditionalLogit( matched["case"], matched[["smoker"]], groups=matched["set"]).fit()density_or = [np.exp(conditional_fit.params["smoker"]), *np.exp(conditional_fit.conf_int().loc["smoker"])]smoker_years = population.loc[population["smoker"] == 1, "years_at_risk"].sum()print(f"{len(density_controls)} control picks of " f"{density_controls['person_id'].nunique()} people, " f"{density_controls['person_id'].isin(cases['person_id']).sum()} " f"picks diagnosed later")print(f"Share of smokers: {density_controls['smoker'].mean():.3f} of " f"picks, {smoker_years / population['years_at_risk'].sum():.3f} of " f"person-years")print(f"Density controls: odds ratio {density_or[0]:.2f} " f"[{density_or[1]:.2f}, {density_or[2]:.2f}], target " f"{truth['Ratio'].iloc[0]:.2f}")Smokers: 348 of 686 cases, 380 of 1372 survivor controlsShare of smokers: 0.304 at enrollment, 0.278 of 3877 survivorsSurvivor controls: odds ratio 2.69 [2.22, 3.25], target 2.711372 control picks of 1248 people, 80 picks diagnosed laterShare of smokers: 0.299 of picks, 0.291 of person-yearsDensity controls: odds ratio 2.48 [2.03, 3.02], target 2.50With survivor controls the odds ratio is 2.69, with an interval from 2.22 to 3.25, and its target is 2.71. That is neither the rate ratio of 2.50 nor the risk ratio of 2.32; it lies next to the odds ratio of the risks, 2.70, which loss to follow-up moves only a little. The reason is in the control group. Smokers were 30.4% of the population at enrollment and are 27.8% of the 3,877 people who reached year 10 without COPD, because smokers leave that group faster. Controls who under-represent the exposure push the odds ratio up.
With density controls the odds ratio is 2.48, with an interval from 2.03 to 3.02, and its target is the rate ratio of 2.50. No rare disease assumption is involved. Controls drawn from the risk sets represent the person-time that produced the cases: 29.9% of the control picks are smokers, and smokers supplied 29.1% of the person-years at risk. The 80 picks of people diagnosed later are correct, since those people were at risk when they were drawn, and removing them would bring back the bias of the first design.
One study of this size cannot tell the two targets apart, and the two intervals overlap almost completely. The difference lies in what the designs estimate, 2.71 against 2.50, and it grows with the risk. When the 10-year risk is a few percent in both groups, nearly everyone under observation is free of the disease, and the rate ratio, the risk ratio and both odds ratios come close together.
A cross-sectional survey
Section titled “A cross-sectional survey”A cross-sectional survey examines a sample of the population at one date and records exposure and disease together. It sees existing cases only, so it estimates prevalence and the prevalence ratio. Survey 1,500 of the 4,300 people present at year 10. The prevalence ratio has the form of a risk ratio and takes the same Wald interval, from riskratio() in epitools and from Table2x2 in statsmodels. The code also computes the true prevalence ratio that equal death rates after the diagnosis would give.
survey <- DrawSample(present, 1500, 2000)survey_table <- table(smoker = survey$smoker, copd = survey$copd)prevalence_ratio <- riskratio(survey_table, method = "wald")$measure[2, ]equal_cases <- rate / (death_rate[1] - rate) * (exp(-10 * rate) - exp(-10 * death_rate[1]))equal_prevalence <- equal_cases / (equal_cases + exp(-10 * rate))cat(sprintf("COPD in %d of %d non-smokers (%.4f), %d of %d smokers (%.4f)\n", survey_table[1, 2], sum(survey_table[1, ]), survey_table[1, 2] / sum(survey_table[1, ]), survey_table[2, 2], sum(survey_table[2, ]), survey_table[2, 2] / sum(survey_table[2, ])))cat(sprintf("Prevalence ratio %.2f, 95%% CI [%.2f, %.2f]\n", prevalence_ratio[1], prevalence_ratio[2], prevalence_ratio[3]))cat(sprintf("True prevalence ratio %.2f; with equal death rates %.2f\n", truth[4, 3], equal_prevalence[2] / equal_prevalence[1]))COPD in 81 of 1044 non-smokers (0.0776), 58 of 456 smokers (0.1272)Prevalence ratio 1.64, 95% CI [1.19, 2.25]True prevalence ratio 1.75; with equal death rates 2.37survey = draw_sample(present, 1500, 2000)survey_counts = survey.groupby("smoker")["copd"].agg(["sum", "size"])survey_2x2 = Table2x2(np.array( [[survey_counts.loc[1, "sum"], survey_counts.loc[1, "size"] - survey_counts.loc[1, "sum"]], [survey_counts.loc[0, "sum"], survey_counts.loc[0, "size"] - survey_counts.loc[0, "sum"]]]))prevalence_ratio = [survey_2x2.riskratio, *survey_2x2.riskratio_confint()]equal_cases = (rate / (death_rate[0] - rate) * (np.exp(-10 * rate) - np.exp(-10 * death_rate[0])))equal_prevalence = equal_cases / (equal_cases + np.exp(-10 * rate))share = survey_counts["sum"] / survey_counts["size"]print(f"COPD in {survey_counts.loc[0, 'sum']} of " f"{survey_counts.loc[0, 'size']} non-smokers ({share[0]:.4f}), " f"{survey_counts.loc[1, 'sum']} of {survey_counts.loc[1, 'size']} " f"smokers ({share[1]:.4f})")print(f"Prevalence ratio {prevalence_ratio[0]:.2f}, 95% CI " f"[{prevalence_ratio[1]:.2f}, {prevalence_ratio[2]:.2f}]")print(f"True prevalence ratio {truth['Ratio'].iloc[3]:.2f}; with equal " f"death rates {equal_prevalence[1] / equal_prevalence[0]:.2f}")COPD in 81 of 1044 non-smokers (0.0776), 58 of 456 smokers (0.1272)Prevalence ratio 1.64, 95% CI [1.19, 2.25]True prevalence ratio 1.75; with equal death rates 2.37The survey finds COPD in 0.0776 of the non-smokers and 0.1272 of the smokers, a prevalence ratio of 1.64 with an interval from 1.19 to 2.25. It is a sound estimate of the true prevalence ratio, 1.75, and the whole interval lies below the rate ratio of 2.50. A reader who takes it as the effect of smoking on getting COPD understates that effect by about a third.
Had smokers and non-smokers with COPD died at the same rate, the true prevalence ratio would have been 2.37. The fall from 2.37 to 1.75 comes from duration alone: smokers with COPD die three times as fast, so fewer of them are alive to be counted. Prevalence mixes how often a disease starts with how long it lasts, and a survey cannot separate the two. An exposure that shortens survival with the disease looks weaker in prevalence data than it is, and an exposure that only prolongs survival looks like a cause.
One table for all the designs
Section titled “One table for all the designs”Collect the five estimates with the measure each one targets.
results <- data.frame( design = c("Cohort", "Cohort", "Case-control, survivor controls", "Case-control, density controls", "Cross-sectional"), measure = c("rate ratio", "risk ratio", "odds ratio", "odds ratio", "prevalence ratio"), rbind(rate_ratio, risk_ratio, survivor_or, density_or, prevalence_ratio), truth = c(truth[1, 3], truth[2, 3], survivor_target, truth[1, 3], truth[4, 3]), target = c("rate ratio", "risk ratio", "survivor odds ratio", "rate ratio", "prevalence ratio"))cat(sprintf("%-31s %-16s %-17s %s\n", "Design", "Measure", "Estimate [95% CI]", "Truth"))cat(sprintf("%-31s %-16s %.2f [%.2f, %.2f] %.2f, the %s\n", results$design, results$measure, results[[3]], results[[4]], results[[5]], results$truth, results$target), sep = "")Design Measure Estimate [95% CI] TruthCohort rate ratio 2.59 [2.05, 3.28] 2.50, the rate ratioCohort risk ratio 2.36 [1.90, 2.93] 2.32, the risk ratioCase-control, survivor controls odds ratio 2.69 [2.22, 3.25] 2.71, the survivor odds ratioCase-control, density controls odds ratio 2.48 [2.03, 3.02] 2.50, the rate ratioCross-sectional prevalence ratio 1.64 [1.19, 2.25] 1.75, the prevalence ratioresults = pd.DataFrame( [rate_ratio, risk_ratio, survivor_or, density_or, prevalence_ratio], columns=["estimate", "lower", "upper"])results["design"] = ["Cohort", "Cohort", "Case-control, survivor controls", "Case-control, density controls", "Cross-sectional"]results["measure"] = ["rate ratio", "risk ratio", "odds ratio", "odds ratio", "prevalence ratio"]results["truth"] = [truth["Ratio"].iloc[0], truth["Ratio"].iloc[1], survivor_target, truth["Ratio"].iloc[0], truth["Ratio"].iloc[3]]results["target"] = ["rate ratio", "risk ratio", "survivor odds ratio", "rate ratio", "prevalence ratio"]print(f"{'Design':<31} {'Measure':<16} {'Estimate [95% CI]':<17} Truth")for row in results.itertuples(): print(f"{row.design:<31} {row.measure:<16} {row.estimate:.2f} " f"[{row.lower:.2f}, {row.upper:.2f}] {row.truth:.2f}, " f"the {row.target}")Design Measure Estimate [95% CI] TruthCohort rate ratio 2.59 [2.05, 3.28] 2.50, the rate ratioCohort risk ratio 2.36 [1.90, 2.93] 2.32, the risk ratioCase-control, survivor controls odds ratio 2.69 [2.22, 3.25] 2.71, the survivor odds ratioCase-control, density controls odds ratio 2.48 [2.03, 3.02] 2.50, the rate ratioCross-sectional prevalence ratio 1.64 [1.19, 2.25] 1.75, the prevalence ratioEvery interval contains the truth of its own row. The five estimates run from 1.64 to 2.69, and none of them is in error. They answer different questions about one exposure in one population, so a ratio quoted without its measure and its design cannot be compared with another. The two odds ratios make the point most directly: the same 686 cases give 2.69 or 2.48, and the only change is the moment at which the controls were sampled.
Mistakes to avoid
Section titled “Mistakes to avoid”Do not call a prevalence a risk. Among smokers the prevalence of COPD at year 10 is 0.1383 and the 10-year risk is 0.2180. The first counts the cases who are alive on one date. The second counts everyone who became a case, and 149 of the 348 smokers with a diagnosis had died before that date.
Do not read a case-control odds ratio as a risk ratio without asking how the controls were sampled. With survivor controls the odds ratio was 2.69 where the risk ratio is 2.32, and with density controls it was 2.48, an estimate of the rate ratio. A methods section that says only “controls were people without the disease” leaves the measure undefined.
Do not report a rate without person-time. Cases divided by people and by the length of the study gave 8.09 per 1,000 for non-smokers where the rate is 9.76, and the error differs between the exposure groups.
Do not compute a risk as cases over people when some were lost to follow-up. That gave smokers a 10-year risk of 0.1910 with an interval that excluded the true 0.2212. Use the Kaplan-Meier estimate, and when deaths from other causes remove people before the diagnosis, use the methods on the competing risks page.
Do not compare crude rates between populations with different age structures. This population had no age in it. Real ones do, and the age standardization page deals with that comparison.
Scientific references
Section titled “Scientific references”The epitools package by Aragon computes risk ratios, odds ratios and rate ratios with their intervals from epidemiologic tables.
The survival package by Therneau supplies the Kaplan-Meier, Cox, and parametric survival models in R.
Davidson-Pilon, 2019 describes lifelines, the Python library for survival analysis.
Miettinen, 1976 shows that a case-referent study can estimate the ratio of incidence densities without a rare disease assumption.
Knol and colleagues, 2008 examine 150 published case-control studies and work out, from the way cases and controls were selected, whether each odds ratio can be read as a rate ratio or as a risk ratio.
Freeman and Hutchison, 1980 describe how prevalence, incidence and duration determine one another in a steady-state population.
Further reading
Section titled “Further reading”The R documentation of clogit() describes conditional logistic regression for matched sets, the model that analyzes the density-sampled controls on this page. The statsmodels documentation of ConditionalLogit covers the same model in Python, with the groups argument that names the matched sets.
The lifelines documentation of KaplanMeierFitter lists the attributes that hold the survival function and its confidence limits.
The risk measures page gives the interval formulas for the risk ratio, the odds ratio and the rate ratio, and pools strata with the Mantel-Haenszel method. The Kaplan-Meier page covers censoring and the estimator used here for the 10-year risk.
The case-control page continues with matched designs and conditional logistic regression, and the age standardization page compares rates across populations of different ages.