Skip to content

Target Trial Emulation

An observational comparison of two treatments answers a causal question only as far as it copies the randomized trial of that question. Target trial emulation makes the copy explicit. You write the protocol of the trial you would run, then build the database analysis to match it row by row. The largest errors in studies of drug effects come from a mismatch in eligibility, in treatment assignment or in the start of follow-up, and a better regression model does not repair them.

This page writes one protocol, breaks its rows in three ways to measure what each mistake costs, and then runs the emulation. Every estimate is printed beside the true value from the simulation that produced the data.

The question is whether patients with a new diagnosis of a chronic lung disease should start a drug at the diagnosis visit. The second column of the table is the trial that would answer it. The third column is the closest copy that a health records database allows.

Protocol component Target trial Emulation in the database
Eligibility A new diagnosis, no contraindication to the drug, no earlier use of the drug The same criteria, read from the record of the diagnosis visit. No patient in this database used the drug before the diagnosis
Treatment strategies (1) Start the drug at the diagnosis visit. (2) Do not start it at that visit. After the visit, care is left to the physician under both strategies The same. A patient with a prescription at the visit follows strategy 1, and every other eligible patient follows strategy 2, whatever happens later
Assignment Random, 1:1, at the diagnosis visit The strategy that the record shows at the visit. Randomization is replaced by an assumption: among patients with the same severity score and age, the choice was as good as random
Time zero The diagnosis visit, where eligibility is met and the strategy is assigned The diagnosis visit, for both groups
Outcome Death from any cause Death from any cause
Follow-up From time zero until death or 60 months From time zero until death or 60 months
Causal contrast The intention-to-treat effect of assignment to strategy 1 instead of strategy 2 The observational analog: the effect of a start at diagnosis against no start at diagnosis, averaged over all eligible patients
Analysis A Cox model with the arm as its only covariate, and the risk of death in each arm at 12 and 60 months with the risk difference The same analysis, weighted by the inverse probability of the observed strategy given severity and age, with robust standard errors

Three rows carry most of the weight. Eligibility, assignment and time zero must fall on the same day, and the strategy must be read from information that exists on that day.

Strategy 2 allows a later start, so the contrast is “drug now” against “no drug now, usual care afterward”. Many clinical questions concern strategies that take time to complete, such as “start within three months”, and a patient’s record at time zero is then compatible with both arms. The clone-censor-weight approach copies each patient into both arms, censors a copy when the record departs from its strategy and weights the remaining follow-up, as the tutorial of Maringe and colleagues, 2020 shows step by step. When patients become eligible on many dates, a sequence of emulated trials, one for each month, gives each of them a time zero, as in the analysis of Hernán and colleagues, 2008.

Download lung_disease_registry.csv and target_trial_truth.csv into your working directory. Both tables are invented.

The registry has 3,500 rows, one per patient with a new diagnosis, and eight columns. patient_id numbers the patients. diagnosis_month is the calendar month of the diagnosis, counted from the opening of the database, from 0 to 35. age, severity and contraindication come from the diagnosis visit: the severity score runs from 0 to 10, and contraindication is 1 for a patient who cannot take the drug. start_month is the time from diagnosis to the first prescription in months. It is 0 for a start at the diagnosis visit and empty for a patient who never started. time is the follow-up in months since diagnosis and event is 1 for a death. Every patient is followed for 60 months or until death, and nobody is lost.

The simulation follows four rules. The death rate rises with the severity score and with age. At the diagnosis visit, a physician prescribes the drug more often to a patient with a high severity score and less often to an old patient, and a patient who leaves the visit without it can start later, sooner when sicker. The drug multiplies the death rate by 2.5 during the first 6 months after the start, when adverse reactions concentrate, and halves it after that. A contraindication also raises the death rate and rules out the drug, and the eligibility row removes it. Among eligible patients, severity and age are the only confounders.

The second file holds the true values of the quantities that this page estimates, in the columns quantity, month and value. They come from a simulation of 1,000,000 patients, in which every patient without a contraindication is followed under both strategies of the protocol. Under strategy 2, a simulated patient can start the drug later by the same rule as in the registry.

The first block loads both tables, prints the truths, applies the eligibility row and assigns each patient a strategy from the record of the diagnosis visit.

library(survival)
library(sandwich)
library(ggplot2)
registry <- read.csv("lung_disease_registry.csv")
truth <- read.csv("target_trial_truth.csv")
truth_of <- setNames(truth$value, paste(truth$quantity, truth$month))
dir.create("outputs", showWarnings = FALSE)
#' Print the hazard ratio of one Cox model term beside the truth.
#'
#' @param fit A model from coxph().
#' @param term The name of the coefficient.
#' @param label The text to print before the ratio.
#' @param true_ratio The true hazard ratio of the estimand.
#' @return Invisibly, the hazard ratio, its 95% limits and the truth.
ReportRatio <- function(fit, term, label, true_ratio) {
ratio <- summary(fit)$conf.int[term, c("exp(coef)", "lower .95",
"upper .95")]
cat(sprintf("%s: HR = %.2f, 95%% CI [%.2f, %.2f], truth %.2f\n", label,
ratio[1], ratio[2], ratio[3], true_ratio))
invisible(c(ratio, truth = true_ratio))
}
true_marginal <- truth_of[["hazard_ratio_marginal 60"]]
true_conditional <- truth_of[["hazard_ratio_conditional 60"]]
cat(sprintf("True hazard ratio: marginal %.3f, conditional %.3f\n",
true_marginal, true_conditional))
for (month in c(12, 60)) {
risk <- truth_of[paste(c("risk_start", "risk_no_start"), month)]
cat(sprintf("True risk at %d months: start %.3f, do not start %.3f, %s\n",
month, risk[1], risk[2],
sprintf("difference %.3f", risk[1] - risk[2])))
}
strategies <- c("Start at diagnosis", "Do not start at diagnosis")
eligible <- registry[registry$contraindication == 0, ]
eligible$arm <- as.integer(!is.na(eligible$start_month) &
eligible$start_month == 0)
later <- !is.na(eligible$start_month) & eligible$start_month > 0
cat(sprintf("%d of %d patients are eligible\n", nrow(eligible),
nrow(registry)))
for (arm in c(1, 0)) {
rows <- eligible[eligible$arm == arm, ]
cat(sprintf("%s: %d patients, %d deaths\n", strategies[2 - arm],
nrow(rows), sum(rows$event)))
}
cat(sprintf("%d of them start later, at a median of %.1f months\n",
sum(later), median(eligible$start_month[later])))
True hazard ratio: marginal 0.772, conditional 0.770
True risk at 12 months: start 0.126, do not start 0.091, difference 0.035
True risk at 60 months: start 0.263, do not start 0.338, difference -0.075
3251 of 3500 patients are eligible
Start at diagnosis: 1133 patients, 357 deaths
Do not start at diagnosis: 2118 patients, 648 deaths
644 of them start later, at a median of 23.1 months

The true effect has two parts with opposite signs. A start at diagnosis raises the risk of death by 12 months from 0.091 to 0.126, and lowers the risk by 60 months from 0.338 to 0.263. The difference at 60 months is -0.075, or 7.5 fewer deaths per 100 patients.

No single hazard ratio describes this drug, since it multiplies the death rate by 2.5 for six months and by 0.5 afterward. The truth file gives the hazard ratio that a Cox model returns in the target trial itself over 60 months, a weighted average of the two periods that would change with the length of follow-up. With the arm as the only covariate it is 0.772, the marginal hazard ratio. With severity and age in the model as well it is 0.770, the conditional hazard ratio. The two are different estimands that happen to agree to two decimals here, and each analysis below is compared with the one it targets.

Of the 3,251 eligible patients, 1,133 started at diagnosis. Of the 2,118 who did not, 644 started later and stay in strategy 2, as they would in the trial. The next sections break the protocol on purpose.

Flawed designs 1 and 2: time zero in the wrong place

Section titled “Flawed designs 1 and 2: time zero in the wrong place”

The first shortcut picks a calendar date, here month 36 of the database, and compares the patients who are taking the drug on that date with the patients who are not, from that date on. This is a prevalent-user design. The second shortcut keeps the diagnosis visit as time zero for everyone and sorts the patients by whether they ever started the drug. Both Cox models adjust for severity and age, so the confounding by those two variables is removed.

eligible$since_diagnosis <- 36 - eligible$diagnosis_month
started_before <- !is.na(eligible$start_month) &
eligible$start_month < eligible$since_diagnosis
alive_at_index <- eligible$time > eligible$since_diagnosis
prevalent <- eligible[alive_at_index, ]
prevalent$current_user <- as.integer(started_before[alive_at_index])
prevalent$time_after <- prevalent$time - prevalent$since_diagnosis
users <- prevalent[prevalent$current_user == 1, ]
months_of_use <- users$since_diagnosis - users$start_month
cat(sprintf("%d patients alive at the index date: %d users, %d non-users\n",
nrow(prevalent), nrow(users), sum(prevalent$current_user == 0)))
cat(sprintf("%d patients started before the index date, %d died before it\n",
sum(started_before), sum(started_before & !alive_at_index)))
cat(sprintf("Months of use at the index date: median %.1f, %d %s\n",
median(months_of_use), sum(months_of_use > 6),
"users above 6"))
prevalent_fit <- coxph(Surv(time_after, event) ~ current_user + severity +
age, data = prevalent)
prevalent_ratio <- ReportRatio(prevalent_fit, "current_user",
"Prevalent users", true_conditional)
eligible$ever_started <- as.integer(!is.na(eligible$start_month))
cat(sprintf("%d later starters waited %.0f patient-months for the drug\n",
sum(later), sum(eligible$start_month[later])))
ever_fit <- coxph(Surv(time, event) ~ ever_started + severity + age,
data = eligible)
ever_ratio <- ReportRatio(ever_fit, "ever_started", "Ever started",
true_conditional)
2816 patients alive at the index date: 1174 users, 1642 non-users
1395 patients started before the index date, 221 died before it
Months of use at the index date: median 15.0, 917 users above 6
Prevalent users: HR = 0.56, 95% CI [0.47, 0.68], truth 0.77
644 later starters waited 16400 patient-months for the drug
Ever started: HR = 0.54, 95% CI [0.47, 0.61], truth 0.77

The prevalent-user hazard ratio is 0.56, with a 95% interval from 0.47 to 0.68 that excludes the true 0.77. The design sees few of the months in which the drug does harm. Of the 1,395 patients who started before the index date, 221 died before it and are missing from the analysis. The 1,174 users who remain have taken the drug for a median of 15.0 months, and 917 of them for more than 6 months, so most of their follow-up begins after the period of raised risk.

Two rows of the protocol are broken. Follow-up starts long after the strategy started, so time zero is wrong, and a user enters only by surviving on the drug until the index date, so eligibility depends on what happened after treatment began. A real database adds a third problem that this one does not show: covariates read at the index date can already be changed by the drug.

The ever-started hazard ratio is 0.54, with an interval from 0.47 to 0.61 that is narrower and also excludes the truth. The 644 later starters spent 16,400 patient-months between the diagnosis and the first prescription. No death can fall in those months, because a patient who dies before starting is never labeled as a starter, and the model counts the months as time on the drug. This is immortal time bias. The broken row is assignment, since “ever started” cannot be written in the record on the day of the diagnosis. The time-dependent covariates page takes the bias apart and removes it with a time-dependent treatment covariate and with a landmark analysis.

Flawed design 3: new users without adjustment

Section titled “Flawed design 3: new users without adjustment”

The third design gets eligibility and time zero right. It compares the patients who started at diagnosis with those who did not, follows both groups from the diagnosis visit, and classifies them with the information of that day. This is the new-user design. Its flaw is in the assignment row, since it treats the two groups as if a coin had formed them.

for (arm in c(1, 0)) {
rows <- eligible[eligible$arm == arm, ]
cat(sprintf("%s: mean severity %.2f, mean age %.1f\n",
strategies[2 - arm], mean(rows$severity), mean(rows$age)))
}
crude_fit <- coxph(Surv(time, event) ~ arm, data = eligible)
crude_ratio <- ReportRatio(crude_fit, "arm", "New users, unadjusted",
true_marginal)
Start at diagnosis: mean severity 5.82, mean age 64.9
Do not start at diagnosis: mean severity 4.51, mean age 66.7
New users, unadjusted: HR = 1.08, 95% CI [0.95, 1.23], truth 0.77

The hazard ratio is 1.08, with an interval from 0.95 to 1.23. The interval contains 1 and excludes the true 0.77, so a drug that prevents 7.5 deaths per 100 patients over five years looks useless.

The patients who started at diagnosis had a mean severity of 5.82 against 4.51 in the others, and severity raises the death rate. Physicians gave the drug to the sicker patients, which is confounding by indication. The starters were also younger, 64.9 against 66.7 years, which works in the opposite direction.

The emulation keeps the new-user design and replaces the coin with a model of the prescription. A logistic regression estimates each patient’s probability of a start at diagnosis from severity and age, the propensity score. Each patient then receives one over the probability of the strategy that the patient followed as a weight. In the weighted population, severity and age no longer predict the strategy, as randomization would have ensured for these two variables.

A Cox model on the weighted population with the arm as its only covariate estimates the marginal hazard ratio of the protocol. A weight makes one patient stand for several, so the model-based standard error is wrong. coxph() switches to a robust sandwich standard error by default when the weights are not integers, and the code writes robust = TRUE to show it; lifelines needs robust=True. The last model in the block takes the outcome regression route instead: an unweighted Cox model with severity and age as covariates, which targets the conditional hazard ratio.

#' Compute inverse probability weights for the two strategies.
#'
#' @param formula The propensity model, with arm on the left side.
#' @param data The eligible patients.
#' @return One weight per patient: one over the fitted probability of the
#' strategy that the patient followed.
StrategyWeights <- function(formula, data) {
probability <- fitted(glm(formula, family = binomial, data = data))
ifelse(data$arm == 1, 1 / probability, 1 / (1 - probability))
}
eligible$weight <- StrategyWeights(arm ~ severity + age, eligible)
cat(sprintf("Weights from %.2f to %.2f\n", min(eligible$weight),
max(eligible$weight)))
for (arm in c(1, 0)) {
rows <- eligible[eligible$arm == arm, ]
cat(sprintf("%s: sum of weights %.0f, weighted mean %s %.2f, %s %.1f\n",
strategies[2 - arm], sum(rows$weight), "severity",
weighted.mean(rows$severity, rows$weight), "age",
weighted.mean(rows$age, rows$weight)))
}
weighted_fit <- coxph(Surv(time, event) ~ arm, data = eligible,
weights = weight, robust = TRUE)
weighted_ratio <- ReportRatio(weighted_fit, "arm", "New users, weighted",
true_marginal)
adjusted_fit <- coxph(Surv(time, event) ~ arm + severity + age,
data = eligible)
adjusted_ratio <- ReportRatio(adjusted_fit, "arm", "New users, adjusted",
true_conditional)
Weights from 1.03 to 22.77
Start at diagnosis: sum of weights 3271, weighted mean severity 4.94, age 66.2
Do not start at diagnosis: sum of weights 3251, weighted mean severity 4.97, age 66.1
New users, weighted: HR = 0.80, 95% CI [0.69, 0.93], truth 0.77
New users, adjusted: HR = 0.80, 95% CI [0.70, 0.92], truth 0.77

The weights run from 1.03 to 22.77. Their sum is 3,271 in the first arm and 3,251 in the second, so each weighted arm stands for the 3,251 eligible patients, as each arm of a trial stands for the whole trial population. The weighted mean severity is 4.94 and 4.97, where the unweighted means were 5.82 and 4.51.

The weighted hazard ratio is 0.80, with an interval from 0.69 to 0.93 that contains the true marginal value of 0.77. The Cox model with covariates also gives 0.80, with an interval from 0.70 to 0.92 around the true conditional value of 0.77. The two routes share the design and the two confounders, and they agree.

The largest weight, 22.77, belongs to a patient whose observed strategy had an estimated probability of 1 / 22.77, or 4.4%, and that one patient stands for almost 23. Read the range of the weights before the estimate. The propensity scores page covers the overlap of the scores, the balance table and the effective sample size. The sandwich standard error treats the weights as known numbers, and a bootstrap that refits the propensity model in each resample also accounts for their estimation.

A hazard ratio does not say how many deaths the drug prevents, or when. The second scale of the protocol is the risk of death by a fixed month under each strategy, with the difference between the two. survfit() and KaplanMeierFitter accept the weights and return the weighted survival curve of each arm.

Nobody in this registry is censored before month 60. The weighted Kaplan-Meier risk at a month is then the weighted share of patients who died by that month, and a weighted linear model of that death indicator on the arm gives the risk difference. vcovHC() from sandwich and cov_type="HC0" in statsmodels give it the same kind of robust standard error as the Cox model. With censoring, read the risks from the weighted curves and take the interval from a bootstrap.

lifelines warns that the weights are not integers and that its naive variance estimates are then biased. The code uses the curves and not their variance.

#' Estimate both risks and the risk difference at one month.
#'
#' @param data The eligible patients, with the columns arm, time and event.
#' @param weight One weight per patient.
#' @param month The month at which to read the risk.
#' @return Both risks, the difference and its 95% limits from the HC0
#' sandwich variance of a weighted linear model.
RiskDifference <- function(data, weight, month) {
data$died <- as.integer(data$event == 1 & data$time <= month)
data$model_weight <- weight
fit <- lm(died ~ arm, data = data, weights = model_weight)
se <- sqrt(vcovHC(fit, type = "HC0")["arm", "arm"])
difference <- coef(fit)[["arm"]]
c(start = sum(coef(fit)), no_start = coef(fit)[["(Intercept)"]],
difference = difference, lower = difference - qnorm(0.975) * se,
upper = difference + qnorm(0.975) * se)
}
curves <- survfit(Surv(time, event) ~ arm, data = eligible,
weights = weight)
curve_risk <- 1 - summary(curves, times = c(12, 60))$surv
cat(sprintf("Weighted Kaplan-Meier risk, %s: %.3f and %.3f\n",
tolower(rev(strategies)), curve_risk[c(1, 3)],
curve_risk[c(2, 4)]), sep = "")
for (month in c(12, 60)) {
risk <- RiskDifference(eligible, eligible$weight, month)
true_risk <- truth_of[paste(c("risk_start", "risk_no_start"), month)]
cat(sprintf("Month %d: start %.3f, do not start %.3f, %s [%.3f, %.3f]\n",
month, risk[["start"]], risk[["no_start"]],
sprintf("difference %.3f", risk[["difference"]]),
risk[["lower"]], risk[["upper"]]))
cat(sprintf(" Truth: start %.3f, do not start %.3f, difference %.3f\n",
true_risk[1], true_risk[2], true_risk[1] - true_risk[2]))
}
curve_data <- rbind(
data.frame(month = 0, survival = 1, strategy = strategies),
data.frame(month = curves$time, survival = curves$surv,
strategy = rep(rev(strategies), curves$strata))
)
true_points <- truth[truth$quantity %in% c("risk_start", "risk_no_start"), ]
true_points$survival <- 1 - true_points$value
true_points$strategy <- ifelse(true_points$quantity == "risk_start",
strategies[1], strategies[2])
curve_data$strategy <- factor(curve_data$strategy, levels = strategies)
true_points$strategy <- factor(true_points$strategy, levels = strategies)
curve_plot <- ggplot(curve_data, aes(month, survival, color = strategy)) +
geom_step(linewidth = 0.9) +
geom_point(data = true_points, size = 2.2, shape = 21, fill = "white",
stroke = 1, show.legend = FALSE) +
scale_color_manual(values = c("#eb6834", "#2a78d6")) +
scale_x_continuous(breaks = seq(0, 60, 12)) +
coord_cartesian(ylim = c(0.6, 1)) +
labs(x = "Months since diagnosis",
y = "Weighted survival (circles: true survival)", color = NULL) +
theme_minimal(base_size = 12) +
theme(legend.position = "top", panel.grid.minor = element_blank())
ggsave("outputs/target-trial-survival-r.png", curve_plot, width = 6.5,
height = 4.5, dpi = 150, bg = "white")
Weighted Kaplan-Meier risk, do not start at diagnosis: 0.087 and 0.330
Weighted Kaplan-Meier risk, start at diagnosis: 0.120 and 0.266
Month 12: start 0.120, do not start 0.087, difference 0.033 [0.009, 0.056]
Truth: start 0.126, do not start 0.091, difference 0.035
Month 60: start 0.266, do not start 0.330, difference -0.064 [-0.099, -0.029]
Truth: start 0.263, do not start 0.338, difference -0.075

Two weighted survival curves over 60 months, drawn with ggplot2. The curve for a start at diagnosis falls faster during the first 6 months, crosses the curve for no start at diagnosis between months 18 and 24, and ends higher at month 60. Open circles at every sixth month mark the true survival under each strategy and lie on or near the curves.

The weighted Kaplan-Meier curves and the weighted linear model give the same risks: 0.087 and 0.330 without a start at diagnosis, 0.120 and 0.266 with one.

At 12 months a start at diagnosis raises the risk of death by 0.033, with an interval from 0.009 to 0.056, or 3.3 more deaths per 100 patients. The truth is 0.035. At 60 months it lowers the risk by 0.064, with an interval from -0.099 to -0.029, or 6.4 fewer deaths per 100 patients. The truth is -0.075. Both intervals contain the true difference and exclude zero, with opposite signs.

In the figure, the curve of the patients who start at diagnosis drops faster for six months, then flattens. The two curves cross between months 18 and 24, and the gap widens in favor of the drug until month 60. The circles sit on or close to both curves over the whole follow-up.

The hazard ratio of 0.80 carries none of this. It is one number for a drug that raises the risk early and lowers it late, and a trial with 12 months of follow-up would have reported a higher risk of death on the same drug. Hernán, 2010 makes this argument against the hazard ratio as the only summary. Report the curves, or the risks at the times that matter for the decision, beside it.

The emulation aligned eligibility, time zero and the strategies. It did not randomize anyone. The weights balance the variables in the propensity model and nothing else, so the causal reading rests on three assumptions. The data cannot check exchangeability and consistency, and they can check positivity only in part, from the propensity scores and the range of the weights. Conditional exchangeability says that among patients with the same severity and age, those who started and those who did not would have had the same survival under the same strategy, which is the assumption of no unmeasured confounding. Positivity says that every kind of eligible patient had some chance of each strategy; a contraindication makes that chance zero, which is why the eligibility row excludes those patients. Consistency says that “start at diagnosis” is one well-defined intervention, the same in the database as in the trial.

To see the first assumption fail, suppose the database had never recorded the severity score. The analyst can still write the same protocol and weight for age. The block ends with the table of every design on this page.

eligible$weight_age <- StrategyWeights(arm ~ age, eligible)
for (arm in c(1, 0)) {
rows <- eligible[eligible$arm == arm, ]
cat(sprintf("%s: weighted mean severity %.2f, age %.1f\n",
strategies[2 - arm],
weighted.mean(rows$severity, rows$weight_age),
weighted.mean(rows$age, rows$weight_age)))
}
age_only_fit <- coxph(Surv(time, event) ~ arm, data = eligible,
weights = weight_age, robust = TRUE)
age_only_ratio <- ReportRatio(age_only_fit, "arm",
"New users, weighted for age only",
true_marginal)
age_only_risk <- RiskDifference(eligible, eligible$weight_age, 60)
cat(sprintf("Risk difference at 60 months %.3f [%.3f, %.3f], truth %.3f\n",
age_only_risk[["difference"]], age_only_risk[["lower"]],
age_only_risk[["upper"]],
truth_of[["risk_start 60"]] - truth_of[["risk_no_start 60"]]))
ratios <- rbind(prevalent_ratio, ever_ratio, crude_ratio, weighted_ratio,
adjusted_ratio, age_only_ratio)
comparison <- data.frame(
design = c("Prevalent users, adjusted", "Ever started, adjusted",
"New users, unadjusted", "Emulation, weighted",
"Emulation, adjusted", "Emulation without severity"),
patients = c(nrow(prevalent), rep(nrow(eligible), 5)),
deaths = c(sum(prevalent$event), rep(sum(eligible$event), 5)),
hr = round(ratios[, 1], 2),
lower = round(ratios[, 2], 2),
upper = round(ratios[, 3], 2),
truth = round(ratios[, 4], 2)
)
print(comparison, row.names = FALSE)
Start at diagnosis: weighted mean severity 5.83, age 66.1
Do not start at diagnosis: weighted mean severity 4.50, age 66.1
New users, weighted for age only: HR = 1.15, 95% CI [1.01, 1.31], truth 0.77
Risk difference at 60 months 0.027 [-0.007, 0.061], truth -0.075
design patients deaths hr lower upper truth
Prevalent users, adjusted 2816 570 0.56 0.47 0.68 0.77
Ever started, adjusted 3251 1005 0.54 0.47 0.61 0.77
New users, unadjusted 3251 1005 1.08 0.95 1.23 0.77
Emulation, weighted 3251 1005 0.80 0.69 0.93 0.77
Emulation, adjusted 3251 1005 0.80 0.70 0.92 0.77
Emulation without severity 3251 1005 1.15 1.01 1.31 0.77

Age is balanced, at 66.1 years in both weighted arms. Severity is not, at 5.83 against 4.50, and in this scenario the analyst cannot print that line. The hazard ratio is 1.15, with an interval from 1.01 to 1.31, which reads as a harmful drug. The risk difference at 60 months is 0.027, against a true -0.075.

This analysis has the same protocol, the same new-user design and the same time zero as the emulation, and its balance table on the measured variables looks clean. Nothing in the output separates it from the valid analysis. Whether the adjustment set is sufficient depends on how physicians choose the treatment, and the page on confounding and causal diagrams shows how to reason about it. Covariates that change after time zero and drive both later treatment and death need the methods of the marginal structural models page.

Six analyses of one database give hazard ratios from 0.54 to 1.15. The truth column holds the conditional hazard ratio for the rows adjusted by regression and the marginal one for the others, and both round to 0.77. Only the two complete emulations have intervals that contain the truth. The first two rows use the same covariates as the adjusted emulation, and they miss because of eligibility, time zero and assignment. The last row uses the same design as the weighted emulation, and it misses because one confounder is absent. The narrowest interval of the table belongs to “Ever started”, which excludes the truth.

Do not define the treatment group with information from after time zero. “Ever started”, “filled at least two prescriptions”, “adherent for one year” and “completed the course” all need the future. In this database the label “ever started” moved the adjusted hazard ratio from 0.80 to 0.54.

Do not exclude patients for what happens after time zero. Dropping the patients who died in the first months, who had less than a year of follow-up or who switched treatment selects on the outcome or on its causes. The prevalent-user design does this without saying so: the 221 starters who died before the index date were excluded for an event that came after their treatment began.

Do not compare users with non-users when the non-users have no time zero. Here the diagnosis visit gives every patient one. In a study of a long-standing disease, a user has the day of the first prescription and a non-user has no comparable day, and an arbitrary date such as the opening of the database breaks the alignment of eligibility, assignment and follow-up. A sequence of trials gives both groups the same time zero.

Do not report a hazard ratio alone when the effect changes during follow-up. The weighted hazard ratio of 0.80 came with a higher risk of death at 12 months, 0.120 against 0.087.

Hernán and Robins, 2016 describe how to use large observational databases to emulate a target trial when a randomized trial is not available.

Hernán and colleagues, 2016 show that specifying a target trial prevents immortal time bias and other self-inflicted injuries in observational analyses.

Hernán and colleagues, 2008 analyze an observational cohort as a sequence of trials of initiators and non-initiators of hormone therapy, and compare the result with the Women’s Health Initiative trial.

Danaei and colleagues, 2013 review the comparison of initiators with non-initiators as the observational analog of an intention-to-treat analysis, with statins and coronary heart disease as the example.

Ray, 2003 describes new-user designs for the evaluation of medication effects outside of clinical trials.

Maringe and colleagues, 2020 give a step-by-step tutorial of trial emulation with cloning, censoring and weighting in the presence of immortal time bias.

Hernán, 2010 explains that a hazard ratio can change over follow-up and carries a built-in selection bias, and recommends adjusted survival curves.

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.

Zeileis, Köll, and Graham, 2020 describe the clustered covariance estimators of the sandwich package.

The book Causal Inference: What If by Hernán and Robins can be downloaded for free with its code and data. Its three parts cover causal inference without models, with models, and from complex longitudinal data.

The coxph reference documents the weights, robust and cluster arguments, and the lifelines page on survival regression describes weights_col and robust in CoxPHFitter.

On this site, the Kaplan-Meier page covers survival curves and the risk at a fixed time, and the g-computation page standardizes an outcome model to get marginal risks without weights.