Skip to content

Time-dependent Covariates & Immortal Time Bias

In a cohort study, treatment often starts some time after follow-up starts. A patient who starts a drug in month 9 has, by definition, survived 9 months. If the analysis labels that patient as treated from day one, those 9 months count as survival on treatment, and a drug that does nothing looks protective. The error is called immortal time bias.

This page reproduces the bias on a cohort in which the true effect is known to be zero, then removes it with a Cox model that has a time-dependent covariate and with a landmark analysis. It builds on Cox regression and on Kaplan-Meier curves.

Download treatment_start_cohort.csv into your working directory. The invented table holds 400 patients followed from the day of discharge after a hospital stay for heart failure, one row per patient. time is the follow-up in months, event is 1 for a death and 0 for a censored time, and treatment_start is the time in months since discharge at which the patient started a drug. It is empty for a patient who never started.

The times come from a simulation with a known answer. Every patient has the same constant death rate, with a median survival of 24 months, and the drug does not change that rate. The true hazard ratio is 1. Prescription times were drawn independently of survival times, so nothing about a patient’s prognosis decides who starts the drug. A patient is untreated only because the planned start came after death or after the data cutoff, or because no prescription was planned.

The first block loads the table, marks the patients who ever started, and defines a helper that prints one hazard ratio with its interval.

library(survival)
library(ggplot2)
cohort <- read.csv("treatment_start_cohort.csv")
cohort$ever_treated <- as.integer(!is.na(cohort$treatment_start))
dir.create("outputs", showWarnings = FALSE)
#' Print the hazard ratio of one term of a Cox model with its interval.
#'
#' @param fit A model from coxph().
#' @param term The name of the coefficient.
#' @param label The text to print before the ratio.
#' @return Invisibly, the hazard ratio and its 95% limits.
ReportRatio <- function(fit, term, label) {
columns <- c("exp(coef)", "lower .95", "upper .95")
ratio <- summary(fit)$conf.int[term, columns]
cat(sprintf("%s: HR = %.2f, 95%% CI [%.2f, %.2f]\n", label, ratio[1],
ratio[2], ratio[3]))
invisible(ratio)
}
cat(sprintf("%d patients, %d deaths, %d started the drug\n", nrow(cohort),
sum(cohort$event), sum(cohort$ever_treated)))
cat(sprintf("Start month: median %.1f, latest %.1f\n",
median(cohort$treatment_start, na.rm = TRUE),
max(cohort$treatment_start, na.rm = TRUE)))
400 patients, 275 deaths, 224 started the drug
Start month: median 7.5, latest 32.4

The tempting analysis sorts each patient into “ever treated” or “never treated” and fits a Cox model with that label as a baseline covariate.

naive_fit <- coxph(Surv(time, event) ~ ever_treated, data = cohort)
naive_ratio <- ReportRatio(naive_fit, "ever_treated", "Ever treated")
Ever treated: HR = 0.44, 95% CI [0.35, 0.56]

The hazard ratio is 0.44, with a 95% interval from 0.35 to 0.56. Read at face value, the drug more than halves the death rate, and the interval is nowhere near 1. The true ratio is 1. Both tools give the same wrong answer, because the error is in the question and not in the software.

The label “ever treated” uses information from the future. On the day of discharge nobody knows who will start the drug. A patient earns the label only by staying alive until the start, so the months between discharge and the start contain no deaths among treated patients. Those months are the immortal time.

The table below splits the follow-up into three kinds of patient-months and counts the deaths in each. The two lines after it compute the death rate per 100 patient-months under each way of classifying the waiting time.

never <- cohort[cohort$ever_treated == 0, ]
starters <- cohort[cohort$ever_treated == 1, ]
died_waiting <- starters$event == 1 &
starters$time <= starters$treatment_start
periods <- data.frame(
period = c("never treated", "waiting for the drug", "after the start"),
patient_months = c(sum(never$time), sum(starters$treatment_start),
sum(starters$time - starters$treatment_start)),
deaths = c(sum(never$event), sum(died_waiting), sum(starters$event))
)
print(periods, row.names = FALSE)
months <- periods$patient_months
deaths <- periods$deaths
naive_rates <- 100 * c(deaths[1] / months[1],
(deaths[2] + deaths[3]) / (months[2] + months[3]))
period_rates <- 100 * c((deaths[1] + deaths[2]) / (months[1] + months[2]),
deaths[3] / months[3])
cat(sprintf("True rate: %.2f deaths per 100 patient-months\n",
100 * log(2) / 24))
cat(sprintf("Ever treated: untreated %.2f, treated %.2f, ratio %.2f\n",
naive_rates[1], naive_rates[2], naive_rates[2] / naive_rates[1]))
cat(sprintf("By period: untreated %.2f, treated %.2f, ratio %.2f\n",
period_rates[1], period_rates[2],
period_rates[2] / period_rates[1]))
period patient_months deaths
never treated 3269.9 142
waiting for the drug 2013.0 0
after the start 4718.5 133
True rate: 2.89 deaths per 100 patient-months
Ever treated: untreated 4.34, treated 1.98, ratio 0.45
By period: untreated 2.69, treated 2.82, ratio 1.05

The 224 patients who started the drug spent 2013.0 patient-months waiting for it, and none of them died during that time. They could not have died then, because a patient who dies before the start never starts and is counted among the never treated.

The ever-treated analysis puts those 2013.0 death-free months in the treated group. The treated rate falls to 1.98 deaths per 100 patient-months, below the true rate of 2.89. The same months are missing from the untreated group, which keeps all the early deaths and shows a rate of 4.34. The ratio of the two rates is 0.45, close to the Cox estimate of 0.44.

Count the waiting months as untreated time, which is what they were, and the rates become 2.69 and 2.82, with a ratio of 1.05. Nothing else changed between the two lines of output.

The figure draws the follow-up of the first 40 patients in the table, one line per patient.

shown <- cohort[1:40, ]
shown <- shown[order(shown$ever_treated, shown$time), ]
shown$row <- seq_len(nrow(shown))
shown$outcome <- ifelse(shown$event == 1, "Death", "Censored")
shown_never <- shown[shown$ever_treated == 0, ]
shown_starters <- shown[shown$ever_treated == 1, ]
period_levels <- c("Never treated", "Waiting for the drug",
"After the start")
segments <- rbind(
data.frame(row = shown_never$row, from = 0, to = shown_never$time,
period = period_levels[1]),
data.frame(row = shown_starters$row, from = 0,
to = shown_starters$treatment_start,
period = period_levels[2]),
data.frame(row = shown_starters$row,
from = shown_starters$treatment_start,
to = shown_starters$time, period = period_levels[3])
)
segments$period <- factor(segments$period, levels = period_levels)
timeline <- ggplot() +
geom_segment(data = segments, linewidth = 1.4,
aes(x = from, xend = to, y = row, yend = row,
color = period)) +
geom_point(data = shown, aes(x = time, y = row, shape = outcome),
size = 2, stroke = 0.9) +
scale_color_manual(values = c("#1baf7a", "#eb6834", "#2a78d6")) +
scale_shape_manual(values = c(Censored = 1, Death = 4)) +
labs(x = "Months since discharge", y = "Patient", color = NULL,
shape = NULL) +
guides(color = guide_legend(order = 1), shape = guide_legend(order = 2)) +
theme_minimal(base_size = 12) +
theme(axis.text.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor = element_blank(), legend.position = "top",
legend.box = "vertical", legend.margin = margin(0, 0, 0, 0))
ggsave("outputs/immortal-time-r.png", timeline, width = 6.5, height = 6,
dpi = 150, bg = "white")

Follow-up lines for 40 patients, drawn with ggplot2. Never-treated patients have one green line. Each treated patient has an orange line from discharge to the start of the drug and a blue line from the start to the end of follow-up. No orange line ends in a death.

Every orange segment is immortal time. The ever-treated analysis reads each orange and blue line as one treated patient from month 0, although the patient was untreated for the whole orange part. The green lines are short more often than the others, because an early death leaves no time to start the drug.

The repair is to let the treatment covariate change value on the day the drug starts. Each treated patient contributes two rows in counting-process form. The first row covers the interval from discharge to the start, with treated equal to 0 and no death. The second covers the interval from the start to the end of follow-up, with treated equal to 1 and the patient’s outcome. Each interval is open on the left and closed on the right, written (start, stop], so a death at the stop time belongs to the row. A never-treated patient keeps one row.

tmerge() in the survival package builds this table: event() places the death at the end of follow-up, and tdc() creates a covariate that switches from 0 to 1 at treatment_start. In lifelines, to_long_format() adds the start and stop columns, and add_covariate_to_timeline() splits each patient’s row at the time of a covariate change. The printed rows belong to patient P002, who started the drug at 4.1 months and died at 43.8 months.

long <- tmerge(cohort[, c("patient_id", "time", "event")], cohort,
id = patient_id, death = event(time, event),
treated = tdc(treatment_start))
cat(sprintf("%d rows for %d patients\n", nrow(long),
length(unique(long$patient_id))))
long_columns <- c("patient_id", "tstart", "tstop", "death", "treated")
print(long[long$patient_id == "P002", long_columns], row.names = FALSE)
tdc_fit <- coxph(Surv(tstart, tstop, death) ~ treated, data = long)
tdc_ratio <- ReportRatio(tdc_fit, "treated", "Time-dependent")
cat(sprintf("log hazard ratio = %.4f, standard error = %.4f\n",
coef(tdc_fit), sqrt(vcov(tdc_fit)[1, 1])))
breslow_fit <- coxph(Surv(tstart, tstop, death) ~ treated, data = long,
ties = "breslow")
cat(sprintf("log hazard ratio with Breslow ties = %.4f\n",
coef(breslow_fit)))
624 rows for 400 patients
patient_id tstart tstop death treated
P002 0.0 4.1 0 0
P002 4.1 43.8 1 1
Time-dependent: HR = 1.00, 95% CI [0.76, 1.31]
log hazard ratio = -0.0016, standard error = 0.1367
log hazard ratio with Breslow ties = -0.0015

The long table has 624 rows, one for each never-treated patient and two for each of the 224 treated patients. At every death time, the model now compares the patient who died with the patients at risk at that moment, each with the treatment status of that moment. A patient who is still waiting sits in the untreated risk set.

The hazard ratio is 1.00, with an interval from 0.76 to 1.31. The interval contains the true value of 1, and its width says how much this cohort can show. A drug that cut the death rate by a fifth, or raised it by 30%, would also be compatible with the data.

R and lifelines agree to four decimals on the log hazard ratio, -0.0016, and on its standard error, 0.1367. The times are rounded to 0.1 month, so many deaths share a time, and both tools resolve those ties with the Efron approximation by default. The Breslow approximation, which is the default of SAS and Stata, gives -0.0015 in R on this table. The gap is in the fourth decimal on this table. It grows with the number of tied deaths, so name the tie method in a report.

The landmark analysis is the simpler remedy, and it needs no long table. Choose a landmark time before you look at the outcome, keep the patients who are still alive and under observation at that time, classify each of them by the treatment status on that day, and start the clock at the landmark. The status is fixed information on the day the clock starts, so no immortal time can enter. This block uses a landmark of 12 months.

landmark <- 12
at_risk <- cohort[cohort$time > landmark, ]
at_risk$treated_by_landmark <- as.integer(
!is.na(at_risk$treatment_start) & at_risk$treatment_start <= landmark
)
at_risk$time_after <- at_risk$time - landmark
excluded <- cohort[cohort$time <= landmark, ]
late_starters <- at_risk$ever_treated == 1 &
at_risk$treated_by_landmark == 0
cat(sprintf("Kept %d of %d patients: %d treated by month %d, %d not\n",
nrow(at_risk), nrow(cohort), sum(at_risk$treated_by_landmark),
landmark, sum(at_risk$treated_by_landmark == 0)))
cat(sprintf("Excluded %d: %d died and %d were censored by month %d\n",
nrow(excluded), sum(excluded$event), sum(excluded$event == 0),
landmark))
cat(sprintf("%d patients in the untreated group start the drug later\n",
sum(late_starters)))
landmark_fit <- coxph(Surv(time_after, event) ~ treated_by_landmark,
data = at_risk)
landmark_ratio <- ReportRatio(landmark_fit, "treated_by_landmark",
"Landmark at 12 months")
Kept 295 of 400 patients: 136 treated by month 12, 159 not
Excluded 105: 105 died and 0 were censored by month 12
63 patients in the untreated group start the drug later
Landmark at 12 months: HR = 1.06, 95% CI [0.79, 1.44]

Of the 400 patients, 295 were alive and under observation at 12 months, 136 who had started the drug and 159 who had not. The hazard ratio is 1.06, with an interval from 0.79 to 1.44, which again contains the true value of 1.

The estimate answers a narrower question than the time-dependent model. It compares, among patients alive at 12 months, those who had started by then with those who had not, from that day on. Three costs come with it.

  • The 105 patients who died in the first 12 months are excluded. The analysis says nothing about the effect of the drug during that year.
  • The 63 patients who started after month 12 stay in the untreated group for the rest of their follow-up. With a drug that works, their treated months would pull the estimate toward 1. Here the drug does nothing, so the misclassification costs nothing.
  • The result depends on the landmark. A landmark chosen after a look at several candidates favors the result that the analyst prefers, so fix it in the analysis plan and give a clinical reason for it.

The landmark analysis keeps one advantage. The two groups are fixed on the day the clock starts, so Kaplan-Meier curves from the landmark are a fair picture of the comparison. Curves from month 0 by “ever treated” carry the same bias as the first model.

ratios <- rbind(naive_ratio, tdc_ratio, landmark_ratio)
comparison <- data.frame(
analysis = c("Ever treated", "Time-dependent", "Landmark at 12 months"),
patients = c(nrow(cohort), nrow(cohort), nrow(at_risk)),
deaths = c(naive_fit$nevent, tdc_fit$nevent, landmark_fit$nevent),
hazard_ratio = round(ratios[, 1], 2),
lower_95 = round(ratios[, 2], 2),
upper_95 = round(ratios[, 3], 2),
truth = 1
)
print(comparison, row.names = FALSE)
analysis patients deaths hazard_ratio lower_95 upper_95 truth
Ever treated 400 275 0.44 0.35 0.56 1
Time-dependent 400 275 1.00 0.76 1.31 1
Landmark at 12 months 295 170 1.06 0.79 1.44 1

The first row is the only one that excludes the truth, and it has the narrowest interval of the three. A narrow interval around a biased estimate is the dangerous combination, since more patients make the wrong answer look more certain. The time-dependent model uses all 400 patients and all 275 deaths. The landmark analysis uses 295 patients and 170 deaths, and its interval is wider.

Time-dependent covariate or time-varying coefficient

Section titled “Time-dependent covariate or time-varying coefficient”

The two terms sound alike and describe different models, and both use the same long table.

A time-dependent covariate is a covariate whose value changes during follow-up while its effect stays the same. On this page treated switches from 0 to 1 at the start of the drug, and one hazard ratio describes the effect of being on the drug at any time.

A time-varying coefficient belongs to a covariate whose value is fixed while its effect changes. A treatment arm assigned at randomization never changes, but its hazard ratio can be 0.5 in the first year and 0.9 afterward. That is a failure of proportional hazards, and the Cox regression page handles it by splitting the follow-up and fitting one coefficient per period.

  • Do not define exposure with information from after baseline. “Ever treated”, “completed six cycles”, “received a transplant”, and “adherent for one year” all need information from the future. Ask whether the label could have been written in the patient’s file on day zero. If it could not, the label is a time-dependent covariate, and a model that treats it as a baseline covariate grants immortal time.
  • Do not compare the survival of responders with that of non-responders from the start of therapy. A tumor response takes weeks to appear, and a patient who dies before the first assessment is a non-responder by default. Responders therefore outlive non-responders even when response has no link to survival. The landmark method is one valid way to make this comparison. A valid comparison still does not show that the therapy prolongs life, because response can mark the patients who had the better prognosis from the start.
  • Do not read a treatment effect from a time-dependent covariate that follows the disease. In this simulation the start of the drug was independent of prognosis. In a real cohort a physician starts or withholds a drug because of how the patient is doing, and a laboratory value or a performance score moves with the disease. A time-dependent Cox model removes the immortal time and leaves this confounding in place. Its hazard ratio then describes an association between the current state and the death rate, which cannot be read as a treatment effect.
  • Do not take the corrected result as proof of no effect. The time-dependent interval here runs from 0.76 to 1.31. It is compatible with no effect, and it does not rule out a moderate benefit or a moderate harm.

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.

Suissa, 2008 describes the cohort designs that create immortal time bias in studies of drug effects and quantifies the size of the bias.

Levesque and colleagues, 2010 describe immortal time bias in cohort studies, with statins and the progression of diabetes as the example.

Anderson, Cain, and Gelber, 1983 describe the bias in survival comparisons of responders with non-responders and propose two valid methods of analysis.

Fisher and Lin, 1999 review time-dependent covariates in the Cox model and warn that the relationship between the covariate and the outcome over time can bias the estimate.

The tmerge reference documents event(), tdc(), and the other functions that build a counting-process table, including covariates that change more than once.

The survival package ships the vignette “Using Time Dependent Covariates and Time Dependent Coefficients in the Cox Model” by Therneau, Crowson, and Atkinson. Open it with vignette("timedep", package = "survival"). Its second section covers the mistakes that create immortal time, and its fourth section covers time-dependent coefficients.

The lifelines page on time varying survival regression explains the long format, to_long_format(), add_covariate_to_timeline(), and CoxTimeVaryingFitter.

Continue with Competing Risks when a second kind of event can prevent the event of interest.