Time-to-event analysis, step by step
Contents
- Censoring is the whole problem
- Three ways of saying the same thing
- Kaplan–Meier, by hand
- The cohort
- The curve, with a risk table
- Reading the curve: medians, landmarks, RMST
- Comparing two groups
- Bootstrap intervals for quantities with no formula
- From curves to models
- The parametric alternative:
psm - Competing risks, and the question you are actually asking
- Immortal time
- What to remember
Censoring is the whole problem
If every patient in a cohort were followed to death, survival analysis would not exist as a separate subject. You would have a column of numbers, and you would describe it with a mean and a histogram.
What makes time-to-event data its own field is that for some patients you do not know the event time – you only know it is larger than something. The study closed. They moved away. They were enrolled last month. That is right censoring, and the entire machinery exists to use those partial observations instead of throwing them away.
Two things are easy to get wrong before any statistics happen at all.
Time zero must be the same clinical moment for everyone. Patients enter on different calendar dates; the analysis runs on time since that moment. The left panel below is what the data collection looks like, the right panel is what the analysis sees.
sw <- tibble(
id = 1:14,
enrol = c(0.0, 0.3, 0.6, 0.9, 1.1, 1.4, 1.8, 2.0, 2.3, 2.7, 3.0, 3.4, 3.8, 4.1),
fu = c(3.1, 1.4, 4.9, 2.2, 5.0, 0.8, 3.6, 1.9, 2.3, 1.2, 1.5, 1.6, 1.0, 0.7),
event = c(1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0)
) |>
mutate(close = 5.2,
# anyone still alive when the study closes is censored there
fu = pmin(fu, close - enrol),
event = ifelse(enrol + fu >= close - 1e-9, 0, event),
lab = ifelse(event == 1, "death", "censored"))
base_sw <- function(dat, xend_col, x_col) {
ggplot(dat, aes(y = factor(id, levels = 14:1))) +
geom_segment(aes(x = .data[[x_col]], xend = .data[[xend_col]],
yend = factor(id, levels = 14:1)),
colour = pal[["grey"]], linewidth = 1.1) +
geom_point(aes(x = .data[[xend_col]], colour = lab, shape = lab), size = 3) +
scale_colour_manual(values = unname(pal[c("blue", "orange")]), name = NULL) +
scale_shape_manual(values = c(censored = 124, death = 19), name = NULL) +
labs(y = "patient")
}
p1 <- sw |>
mutate(x = enrol, xe = enrol + fu) |>
base_sw("xe", "x") +
geom_vline(xintercept = 5.2, linetype = "dashed", colour = pal[["magenta"]]) +
annotate("text", x = 5.1, y = 13.5, label = "study closes",
hjust = 1, size = 3.2, colour = pal[["magenta"]]) +
labs(title = "Calendar time", x = "years since the study opened")
p2 <- sw |>
mutate(x = 0, xe = fu) |>
base_sw("xe", "x") +
labs(title = "Study time -- what the analysis uses", x = "years since enrolment")
p1 + p2 + plot_layout(guides = "collect") & theme(legend.position = "bottom")

Shifting every patient back to a common origin is what turns the ragged left panel into the right one. Note what happened to the patients enrolled late: they are censored not because anything went wrong but because the study closed first, and their short follow-up carries real information – they had not died by then.
Censoring must be uninformative. The estimators below all assume that a patient censored at time \(t\) has the same future risk as a comparable patient still being followed at \(t\). A patient lost to follow-up because they were too sick to come to clinic violates this, and nothing in the output will tell you so. This is an assumption about why follow-up ended, and it is not testable from the data.
Three ways of saying the same thing
There are three functions in constant use, and they contain identical information. Being fluent in all three is most of the conceptual work.
The survival function is the probability of surviving past \(t\):
\[S(t) = P(T > t)\]
The hazard is the instantaneous event rate among those still at risk – not a probability, a rate, and it can exceed 1:
\[h(t) = \lim_{\delta \to 0} \frac{P(t \le T < t+\delta \mid T \ge t)}{\delta}\]
The cumulative hazard accumulates it, and closes the loop:
\[H(t) = \int_0^t h(u)\,du, \qquad S(t) = \exp\{-H(t)\}\]
That last identity is the one to memorise. Every estimator below is really an estimator of \(H\), converted at the end.
The hazard is where clinical intuition lives, because its shape over time is what you actually know about a disease. Four shapes cover most of medicine:
tg <- seq(0.02, 6, length.out = 400)
haz <- list(
"constant (exponential)" = function(t) rep(0.35, length(t)),
"increasing (Weibull k=1.8)" = function(t) (1.8/4) * (t/4)^0.8,
"decreasing (Weibull k=0.6)" = function(t) (0.6/2) * (t/2)^-0.4,
"bathtub (post-operative)" = function(t) 0.9*exp(-3*t) + 0.06 + 0.02*t^1.6
)
sh <- bind_rows(lapply(names(haz), function(nm) {
h <- haz[[nm]](tg)
H <- cumsum(h) * c(tg[1], diff(tg)) # crude but accurate on this grid
tibble(shape = nm, t = tg, h = h, H = H, S = exp(-H))
})) |>
pivot_longer(c(h, H, S), names_to = "fn", values_to = "value") |>
mutate(fn = factor(fn, levels = c("h", "H", "S"),
labels = c("hazard h(t)", "cumulative hazard H(t)",
"survival S(t) = exp(-H(t))")))
ggplot(sh, aes(t, value, colour = shape)) +
geom_line(linewidth = 1) +
facet_wrap(~ fn, scales = "free_y", nrow = 1) +
scale_colour_manual(values = unname(pal[c("grey", "orange", "blue", "magenta")]),
name = NULL) +
labs(title = "One disease process, three descriptions",
subtitle = "Read left to right: the hazard shape determines everything else",
x = "years", y = NULL) +
theme(legend.position = "bottom")

Reading those rows clinically: a constant hazard is a memoryless process (device failure from random external shock). An increasing hazard is progressive disease – idiopathic pulmonary fibrosis, where each year is worse than the last. A decreasing hazard describes a frail subgroup dying early and leaving a tougher remainder behind. The bathtub is any procedure with perioperative risk: a sharp early spike, a long safe plateau, then late attrition.
Notice that survival curves for all four look broadly similar – all monotonically decreasing, all vaguely exponential-looking. The hazard panel separates them instantly. This is why, when someone shows you overlapping survival curves and says the groups are the same, the right follow-up question is about the hazards.
Kaplan–Meier, by hand
The Kaplan–Meier estimator is simpler than its reputation. Take ten patients with lung cancer, time in months:
toy <- tibble(
id = 1:10,
months = c(3, 5, 5, 7, 9, 12, 14, 14, 20, 24),
dead = c(1, 0, 1, 1, 0, 1, 1, 0, 1, 0))
toy
## # A tibble: 10 × 3
## id months dead
## <int> <dbl> <dbl>
## 1 1 3 1
## 2 2 5 0
## 3 3 5 1
## 4 4 7 1
## 5 5 9 0
## 6 6 12 1
## 7 7 14 1
## 8 8 14 0
## 9 9 20 1
## 10 10 24 0
The idea: at each time a death happens, ask what fraction of those still at risk survived it, then multiply those conditional probabilities together. Censored patients contribute to the risk set up to their censoring time and then quietly leave.
km_tab <- toy |>
filter(dead == 1) |>
count(months, name = "d") |>
mutate(
# at risk = everyone whose follow-up reaches this time, censored or not
n_risk = sapply(months, function(t) sum(toy$months >= t)),
cond = 1 - d / n_risk,
S = cumprod(cond),
# Greenwood's formula for the variance of log S, delta-method'd back
se = S * sqrt(cumsum(d / (n_risk * (n_risk - d)))))
km_tab |> mutate(across(c(cond, S, se), ~ round(.x, 4)))
## # A tibble: 6 × 6
## months d n_risk cond S se
## <dbl> <int> <int> <dbl> <dbl> <dbl>
## 1 3 1 10 0.9 0.9 0.0949
## 2 5 1 9 0.889 0.8 0.126
## 3 7 1 7 0.857 0.686 0.152
## 4 12 1 5 0.8 0.549 0.172
## 5 14 1 4 0.75 0.411 0.176
## 6 20 1 2 0.5 0.206 0.170
Four lines of dplyr. Compare with
survfit:
f_toy <- survfit(Surv(months, dead) ~ 1, data = toy)
all.equal(km_tab$S, summary(f_toy)$surv)
## [1] TRUE
all.equal(km_tab$se, summary(f_toy)$std.err)
## [1] TRUE
Both TRUE – the estimate and Greenwood’s standard error,
reproduced exactly. Two features are worth seeing on the plot:
steps <- bind_rows(tibble(months = 0, S = 1), km_tab |> select(months, S))
cens <- toy |> filter(dead == 0) |>
mutate(S = approx(steps$months, steps$S, xout = months, method = "constant",
rule = 2)$y)
ggplot(steps, aes(months, S)) +
geom_step(linewidth = 1, colour = pal[["blue"]]) +
geom_point(data = km_tab, aes(months, S), colour = pal[["blue"]], size = 2.6) +
geom_point(data = cens, aes(months, S), shape = 124, size = 5,
colour = pal[["orange"]]) +
geom_text(data = km_tab,
aes(label = sprintf("%d/%d", n_risk - d, n_risk)),
vjust = -1.2, nudge_x = -0.75, size = 3.1,
colour = pal[["grey"]]) +
scale_y_continuous(limits = c(0, 1.05), labels = scales::percent) +
scale_x_continuous(breaks = seq(0, 24, 4)) +
labs(title = "Kaplan-Meier for ten patients",
subtitle = paste("Labels are survivors/at-risk at each death.",
"Orange ticks are censored patients."),
x = "months", y = "S(t)")

First, the curve is flat between deaths and drops only at event times. A censored patient causes no drop – it changes the denominator of every later step. That is exactly how the information in censored follow-up gets used.
Second, the steps get larger late in follow-up, because the denominator is small: the drop at 20 months is 50%, computed from two patients. The right tail of a KM curve is almost always unreliable, which is why it should never be read without a risk table. More on that in a moment.
The cohort
For the rest of the post I will use a simulated cohort of 400 patients with idiopathic pulmonary fibrosis, followed from diagnosis for up to six years. Simulating rather than borrowing a real dataset buys one decisive advantage: later on, when two estimators disagree, I can compute which one is right.
The outcomes are death, lung transplant (a competing event – it ends follow-up for death and is not a failure), and administrative censoring.
make_ipf <- function(n = 400, seed = 101) {
set.seed(seed)
age <- round(rnorm(n, 68, 8)); age <- pmin(pmax(age, 45), 88)
sex <- factor(sample(c("male","female"), n, TRUE, c(.72,.28)),
levels = c("female","male"))
fvc <- round(rnorm(n, 72, 14)); fvc <- pmin(pmax(fvc, 35), 115)
dlco <- round(0.55 * fvc + rnorm(n, 18, 9)); dlco <- pmin(pmax(dlco, 20), 100)
# antifibrotic use is CONFOUNDED: better lung function, likelier to be treated
af <- rbinom(n, 1, plogis(-0.3 + 0.040 * (fvc - 72)))
# death: Weibull proportional hazards, shape 1.4 (hazard rises with time)
lp <- 0.045*(age-68) - 0.030*(fvc-72) - 0.012*(dlco-45) - 0.35*af +
0.25*(sex == "male")
t_death <- rweibull(n, 1.4, 4.2 * exp(-lp / 1.4))
# transplant: realistically only under 68, and driven by low FVC
t_tx <- ifelse(age < 68, rweibull(n, 1.1, 5.0*exp(0.055*(fvc-72)/1.1)), Inf)
t_cens <- pmin(rexp(n, 1/14), 6) # dropout, plus 6-year study close
time <- pmin(t_death, t_tx, t_cens)
status <- ifelse(time == t_death, 1L, ifelse(time == t_tx, 2L, 0L))
tibble(age, sex, fvc, dlco,
antifib = factor(ifelse(af == 1, "yes", "no"), levels = c("no","yes")),
time = round(time, 3), status = status)
}
d <- make_ipf()
d$dead <- as.numeric(d$status == 1) # 1 = death, 0 = anything else
count(d, status = factor(status, 0:2, c("censored", "death", "transplant")))
## # A tibble: 3 × 2
## status n
## <fct> <int>
## 1 censored 114
## 2 death 208
## 3 transplant 78
The true antifibrotic effect is a hazard ratio of 0.705, and the drug is preferentially given to patients with better baseline lung function. Both facts will matter.
ggplot(d, aes(fvc, fill = antifib)) +
geom_histogram(binwidth = 5, colour = "white", position = "identity",
alpha = 0.65) +
scale_fill_manual(values = unname(pal[c("orange", "blue")]),
name = "antifibrotic") +
labs(title = "The treated patients were healthier to begin with",
subtitle = sprintf("mean FVC %.1f%% untreated vs %.1f%% treated",
mean(d$fvc[d$antifib == "no"]),
mean(d$fvc[d$antifib == "yes"])),
x = "baseline FVC (% predicted)", y = "patients")

The curve, with a risk table
Harrell’s Hmisc wraps survfit in
npsurv, which keeps the data around so that
survplot and friends work; the estimate itself is the same
Kaplan–Meier.
f <- npsurv(Surv(time, dead) ~ antifib, data = d)
f
## Call: npsurv(formula = Surv(time, dead) ~ antifib, data = d)
##
## n events median 0.95LCL 0.95UCL
## antifib=no 226 130 2.80 2.40 3.65
## antifib=yes 174 78 4.72 3.93 5.68
To draw it in ggplot2, pull the step coordinates out of
the fit. This small helper gets reused all the way through the post:
tidy_km <- function(fit) {
grp <- if (is.null(fit$strata)) rep("all", length(fit$time))
else rep(sub(".*=", "", names(fit$strata)), fit$strata)
tibble(group = grp, time = fit$time, surv = fit$surv,
lo = fit$lower, hi = fit$upper, n.event = fit$n.event) |>
group_by(group) |>
# every curve starts at S(0) = 1; survfit does not store that row
group_modify(~ add_row(.x, time = 0, surv = 1, lo = 1, hi = 1,
n.event = 0, .before = 1)) |>
ungroup()
}
risk_tab <- function(fit, times) {
s <- summary(fit, times = times, extend = TRUE)
tibble(group = sub(".*=", "", as.character(s$strata)),
time = s$time, n.risk = s$n.risk)
}
k <- tidy_km(f)
rt <- risk_tab(f, 0:6)
A survival curve without numbers at risk is half a figure.
patchwork stacks the two with a shared axis:
cols <- unname(pal[c("orange", "blue")])
p_km <- ggplot(k, aes(time, surv, colour = group, fill = group)) +
geom_ribbon(aes(ymin = lo, ymax = hi), alpha = 0.18, colour = NA) +
geom_step(linewidth = 1) +
geom_point(data = filter(k, n.event == 0, time > 0), shape = 124,
size = 2.4, show.legend = FALSE) +
scale_colour_manual(values = cols, name = "antifibrotic") +
scale_fill_manual(values = cols, name = "antifibrotic") +
scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
scale_x_continuous(breaks = 0:6, limits = c(0, 6)) +
labs(title = "Survival from diagnosis, by antifibrotic use",
subtitle = "Shaded bands are pointwise 95% intervals; ticks are censorings",
x = NULL, y = "survival")
p_rt <- ggplot(rt, aes(time, group, label = n.risk)) +
geom_text(aes(colour = group), size = 3.3, show.legend = FALSE) +
scale_colour_manual(values = cols) +
scale_x_continuous(breaks = 0:6, limits = c(0, 6)) +
labs(x = "years since diagnosis", y = NULL, title = NULL) +
theme(panel.grid = element_blank(),
axis.text.y = element_text(hjust = 0))
p_km / p_rt + plot_layout(heights = c(5, 1))

The risk table is what tells you how much to trust the right-hand end. By year 5 the untreated arm is down to 25 patients, and the interval widens accordingly.
A detail in the code worth noting: the censoring ticks are drawn from
rows where n.event == 0. survfit stores a row
for every distinct follow-up time, event or not, and the rows with no
events are the censoring times.
Reading the curve: medians, landmarks, RMST
Three different numbers summarise a survival curve, and they answer three different questions.
tb <- summary(f, rmean = 5)$table
tb[, c("records", "events", "median", "0.95LCL", "0.95UCL", "rmean")] |> round(3)
## records events median 0.95LCL 0.95UCL rmean
## antifib=no 226 130 2.801 2.401 3.649 2.908
## antifib=yes 174 78 4.721 3.934 5.677 3.594
Median survival is the time at which the curve crosses 50%. It is the default summary and has two weaknesses. It is a single point on a whole curve, and – worse – it does not exist if the curve never reaches 50% within follow-up. That is not a rare edge case; it happens in any trial with good survival and short follow-up.
Landmark survival is \(\hat S(t)\) at a clinically chosen time. It is honest about what it reports and easy to communicate:
summary(f, times = c(1, 3, 5))$surv |> matrix(nrow = 2, byrow = TRUE,
dimnames = list(c("no", "yes"), c("1 yr", "3 yr", "5 yr"))) |> round(3)
## 1 yr 3 yr 5 yr
## no 0.841 0.482 0.228
## yes 0.877 0.654 0.479
Restricted mean survival time is the area under the
curve out to a horizon \(\tau\) –
literally \(\int_0^\tau S(u)\,du\), in
units of years of life. It uses the whole curve rather than one point,
it always exists, and it does not need proportional hazards to mean
something. summary(..., rmean = 5) computed it above; here
is what it is, geometrically:
tau <- 5
area <- k |>
filter(time <= tau) |>
group_by(group) |>
group_modify(~ add_row(.x, time = tau, surv = last(.x$surv),
lo = NA, hi = NA, n.event = 0)) |>
# the right edge of each rectangle is the NEXT step within this arm.
# Computing it with lead() inside aes() would run on the ungrouped frame
# and bridge the two arms with one panel-wide rectangle.
mutate(xend = lead(time, default = tau)) |>
ungroup()
rm5 <- tb[, "rmean"]
ggplot(area, aes(time, surv, colour = group, fill = group)) +
geom_step(linewidth = 1) +
geom_rect(aes(xmin = time, xmax = xend, ymin = 0, ymax = surv),
alpha = 0.22, colour = NA) +
facet_wrap(~ group, labeller = labeller(
group = c(no = sprintf("untreated: RMST = %.2f yr", rm5[1]),
yes = sprintf("treated: RMST = %.2f yr", rm5[2])))) +
scale_colour_manual(values = cols, guide = "none") +
scale_fill_manual(values = cols, guide = "none") +
scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
labs(title = "RMST is the shaded area",
subtitle = sprintf(
"Difference = %.2f years of life gained over 5 years of follow-up",
rm5[2] - rm5[1]),
x = "years since diagnosis", y = "survival")

The treated arm averages 3.59 of the 5 available years versus 2.91, a gain of 0.69 years. Note how much more interpretable that is than a hazard ratio, and that it is tied to a stated horizon – change \(\tau\) and you change the number, which is a feature, not a bug.
Comparing two groups
The log-rank test compares observed with expected deaths in each arm, where “expected” is computed under the null at every event time and summed.
lr <- survdiff(Surv(time, dead) ~ antifib, data = d)
lr
## Call:
## survdiff(formula = Surv(time, dead) ~ antifib, data = d)
##
## N Observed Expected (O-E)^2/E (O-E)^2/V
## antifib=no 226 130 98.5 10.06 19.6
## antifib=yes 174 78 109.5 9.05 19.6
##
## Chisq= 19.6 on 1 degrees of freedom, p= 1e-05
\(\chi^2 = 19.6\) on 1 df. Three things about this number.
It is a test, not an estimate. It tells you the curves differ; it does not tell you by how much, and a tiny p-value from a huge trial can accompany a clinically trivial separation. Harrell’s standing advice applies with full force here: report the estimate with its interval, and let the test be a footnote. The landmark differences and the RMST difference above are the estimates.
It is a weighted average over time. The ordinary
log-rank weights every event time equally. survdiff’s
rho argument gives the Harrington–Fleming family, where
rho = 1 weights early differences more:
c(logrank = survdiff(Surv(time, dead) ~ antifib, data = d, rho = 0)$chisq,
gehan_wilcoxon = survdiff(Surv(time, dead) ~ antifib, data = d, rho = 1)$chisq)
## logrank gehan_wilcoxon
## 19.57638 14.05397
And it is only sensible if the difference has a consistent direction. Which brings us to the failure mode.
When the log-rank test goes blind
Consider lung transplant versus medical management for advanced disease: real perioperative mortality, then a much better subsequent course. Here is such a comparison, simulated with 20% perioperative mortality:
set.seed(2024); n <- 250
t_med <- rweibull(n, 1.3, 3.6)
periop <- rbinom(n, 1, 0.20)
t_sur <- ifelse(periop == 1, runif(n, 0, 0.1), rweibull(n, 1.3, 5.4))
c1 <- pmin(rexp(n, 1/20), 7); c2 <- pmin(rexp(n, 1/20), 7)
cr <- bind_rows(
tibble(arm = "medical", time = pmin(t_med, c1), dead = as.numeric(t_med <= c1)),
tibble(arm = "surgical", time = pmin(t_sur, c2), dead = as.numeric(t_sur <= c2))
) |> mutate(arm = factor(arm, levels = c("medical", "surgical")))
lr_cr <- survdiff(Surv(time, dead) ~ arm, data = cr)
cox_cr <- coxph(Surv(time, dead) ~ arm, data = cr)
c(logrank_p = pchisq(lr_cr$chisq, 1, lower.tail = FALSE),
cox_HR = exp(coef(cox_cr)),
cox_p = summary(cox_cr)$coef[1, 5])
## logrank_p cox_HR.armsurgical cox_p
## 0.8545572 1.0192373 0.8545593
The log-rank p-value is 0.85 and the Cox hazard ratio is 1.02. By both summaries there is no difference at all between these two managements. Now look:
f_cr <- survfit(Surv(time, dead) ~ arm, data = cr)
k_cr <- tidy_km(f_cr)
s90 <- summary(f_cr, times = 0.25)
ggplot(k_cr, aes(time, surv, colour = group)) +
geom_step(linewidth = 1) +
annotate("segment", x = 0.25, xend = 0.25, y = s90$surv[2], yend = s90$surv[1],
colour = pal[["magenta"]], linewidth = 0.8,
arrow = arrow(ends = "both", length = unit(0.07, "in"))) +
annotate("text", x = 0.45, y = 0.965, hjust = 0, size = 3.4,
colour = pal[["magenta"]],
label = sprintf("90-day mortality %.0f%% vs %.0f%%",
100*(1-s90$surv[1]), 100*(1-s90$surv[2]))) +
scale_colour_manual(values = unname(pal[c("green", "violet")]), name = NULL) +
scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
labs(title = sprintf("Log-rank p = %.2f, hazard ratio %.2f -- \"no difference\"",
pchisq(lr_cr$chisq, 1, lower.tail = FALSE),
exp(coef(cox_cr))),
subtitle = "Two managements that differ about as much as two managements can",
x = "years", y = "survival")

One in four surgical patients is dead within three months; the survivors then do better, and by year 7 the surgical curve is on top. The early loss and the late gain cancel in the log-rank sum. The medians are 2.83 and 2.93 years – also no help.
This is not an exotic failure. It is the expected behaviour of any single-number summary applied to curves that cross, and it is precisely the situation in which a patient most needs the information. The alarm is cheap:
cox.zph(cox_cr)
## chisq df p
## arm 16.2 1 5.7e-05
## GLOBAL 16.2 1 5.7e-05
\(p = 5.7e-05\) – the proportional hazards test, which I covered in detail in the Cox model post, is emphatic even while the log-rank test shrugs. And the honest summary needs two numbers, not one: 90-day mortality 3% versus 27%, and 7-year survival 13% versus 17%.
Plot the curves before you test them.
Bootstrap intervals for quantities with no formula
Back to the IPF cohort. Greenwood’s formula gives standard errors for \(\hat S(t)\), so the difference in 3-year survival has an easy interval. Many other things you want do not. The bootstrap – resampling patients with replacement, recomputing everything – works for all of them, and Harrell leans on it heavily. Resample within arms to preserve the design:
diff_3yr <- function(data, i) {
s <- data[i, ]
v <- summary(survfit(Surv(time, dead) ~ antifib, data = s),
times = 3, extend = TRUE)$surv
if (length(v) != 2) return(NA_real_) # an arm could resample to nothing
v[2] - v[1]
}
set.seed(7)
bo <- boot(as.data.frame(d), diff_3yr, R = 2000, strata = d$antifib)
ci <- boot.ci(bo, type = c("perc", "bca", "basic"))
ci
## BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
## Based on 2000 bootstrap replicates
##
## CALL :
## boot.ci(boot.out = bo, type = c("perc", "bca", "basic"))
##
## Intervals :
## Level Basic Percentile BCa
## 95% ( 0.0638, 0.2806 ) ( 0.0636, 0.2804 ) ( 0.0639, 0.2818 )
## Calculations and Intervals on Original Scale
Compare with the Greenwood-based interval, treating the two arms as independent:
su <- summary(f, times = 3)
se_diff <- sqrt(sum(su$std.err^2))
c(estimate = bo$t0,
greenwood_lo = bo$t0 - 1.96*se_diff, greenwood_hi = bo$t0 + 1.96*se_diff,
boot_se = sd(bo$t, na.rm = TRUE), greenwood_se = se_diff) |> round(4)
## estimate greenwood_lo greenwood_hi boot_se greenwood_se
## 0.1721 0.0621 0.2820 0.0555 0.0561
They agree closely – 0.062 to 0.282 against a percentile interval of 0.064 to 0.280. That is the honest result, and it is worth saying plainly: for a difference in landmark survival with a few hundred events, the closed-form interval is fine and the bootstrap buys you nothing. Do not let a tutorial talk you into 2000 resamples you did not need.
Where the bootstrap does earn its place is a statistic with no usable variance formula. The difference in median survival is one:
diff_med <- function(data, i) {
tb <- summary(survfit(Surv(time, dead) ~ antifib, data = data[i, ]))$table
if (nrow(tb) != 2) return(NA_real_)
tb[2, "median"] - tb[1, "median"]
}
set.seed(7)
bm <- boot(as.data.frame(d), diff_med, R = 2000, strata = d$antifib)
c(estimate = bm$t0, failed_replicates = sum(is.na(bm$t)))
## estimate failed_replicates
## 1.92 24.00
boot.ci(bm, type = c("perc", "bca"))
## BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
## Based on 1976 bootstrap replicates
##
## CALL :
## boot.ci(boot.out = bm, type = c("perc", "bca"))
##
## Intervals :
## Level Percentile BCa
## 95% ( 0.702, 2.946 ) ( 0.756, 3.001 )
## Calculations and Intervals on Original Scale
The point estimate is 1.92 years with a percentile interval of
roughly 0.70 to 2.95. But look at failed_replicates: in 24
of 2000 resamples the treated arm’s curve never reached 50% and the
median was NA. boot.ci drops them without
comment and reports an interval from the rest – so the interval is
implicitly conditional on the median being estimable, which is not quite
the thing you asked for. The same fragility shows in the shape of the
two distributions:
bd <- bind_rows(
tibble(stat = "difference in 3-year survival", v = as.numeric(bo$t)),
tibble(stat = "difference in median survival (years)", v = as.numeric(bm$t)))
ggplot(bd, aes(v)) +
geom_histogram(bins = 45, fill = pal[["blue"]], colour = "white") +
geom_vline(data = tibble(stat = unique(bd$stat), t0 = c(bo$t0, bm$t0)),
aes(xintercept = t0), colour = pal[["orange"]], linewidth = 1) +
facet_wrap(~ stat, scales = "free") +
labs(title = "2000 bootstrap replicates, resampled within arms",
subtitle = paste("Left: smooth and near-Gaussian.\nRight: visibly lumpy,",
"because a KM median can only land on an observed",
"event time"),
x = NULL, y = "replicates")

The left histogram is smooth, which is why the normal-theory interval worked. The right one is lumpy: a Kaplan–Meier median can only ever be one of the observed event times, so the bootstrap distribution is a pile of atoms. That is also a warning about the BCa interval, whose acceleration estimate is jumpy for discrete statistics.
From curves to models
Kaplan–Meier handles one categorical predictor. The moment you need to adjust for anything, you need a model – and the comparison above is badly confounded, because the treated patients started with better lung function.
crude <- coxph(Surv(time, dead) ~ antifib, data = d)
adj <- coxph(Surv(time, dead) ~ antifib + age + sex + fvc + dlco, data = d)
rbind(crude = c(HR = exp(coef(crude)[1]), exp(confint(crude)[1, ])),
adjusted = c(HR = exp(coef(adj)[1]), exp(confint(adj)[1, ]))) |> round(3)
## HR.antifibyes 2.5 % 97.5 %
## crude 0.532 0.400 0.707
## adjusted 0.707 0.526 0.949
The crude hazard ratio is 0.532; adjusted for age, sex, FVC and DLCO
it is 0.707. The true value built into the simulation is 0.705. The
crude estimate overstates the benefit by roughly a third, and adjustment
recovers the truth almost exactly – which is the entire argument for
modelling rather than stratifying, and why rms::cph and its
diagnostics get their
own post.
With only three or four predictors and 208 events, this model is nowhere near overfitting:
dd <- datadist(d); options(datadist = "dd")
fc <- cph(Surv(time, dead) ~ antifib + age + fvc, data = d,
x = TRUE, y = TRUE, surv = TRUE)
set.seed(3)
validate(fc, B = 150)[c("Dxy", "Slope"), ] |> round(4)
## index.orig training test optimism index.corrected Lower Upper n
## Dxy 0.3226 0.3215 0.3202 0.0013 0.3213 0.2386 0.4107 150
## Slope 1.0000 1.0000 0.9953 0.0047 0.9953 0.7428 1.3104 150
The bootstrap-corrected \(D_{xy}\) barely moves from the apparent value and the calibration slope is essentially 1. Contrast that with the heavily splined 9-degree-of-freedom model in the Cox post, whose slope shrank to 0.73: the difference is degrees of freedom spent per event, nothing else.
The parametric alternative: psm
Cox leaves the baseline hazard unspecified. If you are willing to
name a distribution you get a smooth survival curve, extrapolation
beyond follow-up, and more efficiency when the choice is right.
rms::psm fits these as accelerated failure time models:
dists <- c("weibull", "lognormal", "loglogistic", "exponential")
sapply(dists, function(dt)
AIC(psm(Surv(time, dead) ~ antifib + age + fvc, data = d, dist = dt))) |>
round(1)
## weibull lognormal loglogistic exponential
## 999.0 1021.3 1011.5 1027.9
Weibull wins, as it should – that is how the data were generated. Never trust a simulation to validate a method without checking it also picks the wrong answers correctly, and here the exponential, which forces a constant hazard onto a rising one, is penalised by 29 AIC units.
fw <- psm(Surv(time, dead) ~ antifib + age + fvc, data = d, dist = "weibull")
fw
## Parametric Survival Model: Weibull Distribution
##
## psm(formula = Surv(time, dead) ~ antifib + age + fvc, data = d,
## dist = "weibull")
##
## Model Likelihood Discrimination
## Ratio Test Indexes
## Obs 400 LR chi2 79.28 R2 0.193
## Events 208 d.f. 3 R2(3,400)0.174
## sigma 0.7254 Pr(> chi2) <0.0001 R2(3,208)0.307
## Dxy 0.343
##
## Coef S.E. Wald Z Pr(>|Z|)
## (Intercept) 1.8237 0.5696 3.20 0.0014
## antifib=yes 0.2783 0.1075 2.59 0.0096
## age -0.0336 0.0073 -4.60 <0.0001
## fvc 0.0258 0.0041 6.23 <0.0001
## Log(scale) -0.3211 0.0556 -5.77 <0.0001
The Weibull is the one distribution that is both an AFT model and a proportional hazards model, so its coefficients convert. With scale \(\sigma\), the hazard ratio is \(\exp(-\beta/\sigma)\):
# fw$scale is sigma. Do NOT use exp(fw$icoef[2]) -- that is a different
# internal parameterisation and gives a silently wrong answer.
sigma <- fw$scale
rbind(from_weibull_AFT = exp(-coef(fw)[c("antifib=yes","age","fvc")] / sigma),
from_cph = exp(coef(fc)[c("antifib=yes","age","fvc")])) |> round(4)
## antifib=yes age fvc
## from_weibull_AFT 0.6813 1.0474 0.9650
## from_cph 0.6810 1.0476 0.9648
c(weibull_shape = 1/sigma, truth = 1.4) |> round(3)
## weibull_shape truth
## 1.379 1.400
Identical to three decimals, from two completely different likelihoods. The recovered shape is 1.379 against a true 1.4.
Does the parametric curve actually fit? Overlay it on the Kaplan–Meier – the only check that matters. For a fair comparison the parametric model must predict the same thing the KM curve estimates, so for this figure alone I drop the continuous covariates and fit on arm only:
# as.data.frame is NOT cosmetic here: predictrms indexes newdata with
# `nd[, "antifib"]`, which on a tibble returns a one-column tibble rather than
# a vector, and the factor-level check then fails with a baffling
# "Values in antifib not in no yes".
nd <- data.frame(antifib = factor(c("no", "yes"), levels = c("no", "yes")))
tg <- seq(0, 6, length.out = 300)
para <- bind_rows(lapply(c("weibull", "lognormal", "exponential"), function(dt) {
m <- psm(Surv(time, dead) ~ antifib, data = d, dist = dt)
sf <- Survival(m)
lp <- predict(m, nd)
bind_rows(lapply(1:2, function(i)
tibble(dist = dt, group = as.character(nd$antifib[i]),
time = tg, surv = sf(tg, lp = lp[i]))))
}))
ggplot(para, aes(time, surv)) +
geom_step(data = k, aes(group = group), colour = pal[["grey"]],
linewidth = 1) +
geom_line(aes(colour = dist), linewidth = 0.9) +
facet_wrap(~ group, labeller = labeller(
group = c(no = "untreated", yes = "antifibrotic"))) +
scale_colour_manual(values = unname(pal[c("magenta", "green", "blue")]),
name = "parametric fit") +
scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
labs(title = "Parametric fits against the Kaplan-Meier (grey steps)",
subtitle = "Arm-only models, so the parametric curve and the KM curve estimate the same quantity",
x = "years since diagnosis", y = "survival")

The Weibull tracks the steps closely across the whole range. The exponential, forced to a constant hazard, is too pessimistic in the first two years and too optimistic after four – exactly the signature of fitting a straight cumulative hazard to a curved one. The lognormal, whose hazard eventually turns back down, drifts above the data late in the untreated arm. That is the AIC ranking made visible, and it is the check to run before trusting any extrapolation beyond follow-up, which is the main reason to fit a parametric model at all.
There is also a graphical check specific to the Weibull. If \(S(t) = \exp\{-(t/b)^a\}\) then \(\log\{-\log S(t)\} = a \log t - a \log b\), a straight line with slope \(a\):
cl <- tibble(t = f$time, s = f$surv,
group = rep(sub(".*=", "", names(f$strata)), f$strata)) |>
filter(s > 0, s < 1)
slopes <- cl |>
group_by(group) |>
summarise(slope = coef(lm(log(-log(s)) ~ log(t)))[2],
r2 = summary(lm(log(-log(s)) ~ log(t)))$r.squared)
ggplot(cl, aes(log(t), log(-log(s)), colour = group)) +
geom_point(alpha = 0.7, size = 1.5) +
geom_smooth(method = "lm", se = FALSE, linewidth = 0.9) +
scale_colour_manual(values = cols, name = "antifibrotic") +
labs(title = "Complementary log-log: straight means Weibull, parallel means proportional",
subtitle = sprintf("slopes %.2f (untreated) and %.2f (treated)",
slopes$slope[1], slopes$slope[2]),
x = "log(time)", y = "log(-log S(t))")

This one plot checks two assumptions at once. Straight says the Weibull shape is reasonable, and both arms are (\(R^2\) 0.996 and 0.969). Parallel says the hazards are proportional, since under \(h_1(t) = \psi\, h_0(t)\) the two lines differ only by the constant \(\log \psi\). The fitted slopes are 1.29 and 1.30 – as parallel as one could ask for, which is correct, because the data were generated under proportional hazards.
One honest wrinkle: those slopes are near 1.29, not the 1.4 built into the generator. That is not an error. A mixture of patients with different Weibull hazards is not itself Weibull, and averaging over a heterogeneous cohort flattens the apparent shape. The model fitted conditionally on covariates recovered 1.38. Check distributional assumptions on the conditional fit; read the marginal curve for the parallelism, not the slope.
Competing risks, and the question you are actually asking
Now the part that is most often done wrong. 78 of our patients received a lung transplant. The Kaplan–Meier above treated transplant as censoring. Was that right?
Censoring means “this patient’s future risk is represented by those still being followed.” A transplanted patient’s future risk of dying of pulmonary fibrosis is not represented by anyone – they no longer have the disease. The event has removed them from the possibility of the outcome rather than merely hidden it.
The right tool is the cumulative incidence function,
estimated by Aalen–Johansen. In modern survival you get it
by passing a factor status to Surv, with the first
level meaning censored:
d$ev <- factor(d$status, 0:2, labels = c("censored", "death", "transplant"))
aj <- survfit(Surv(time, ev) ~ 1, data = d)
aj$states
## [1] "(s0)" "death" "transplant"
summary(aj, times = c(1, 3, 5))$pstate |>
`colnames<-`(aj$states) |> `rownames<-`(c("1 yr", "3 yr", "5 yr")) |> round(4)
## (s0) death transplant
## 1 yr 0.7831 0.1355 0.0814
## 3 yr 0.4265 0.3819 0.1916
## 5 yr 0.2536 0.5417 0.2047
Against the naive one-minus-Kaplan–Meier:
km_all <- summary(survfit(Surv(time, dead) ~ 1, data = d), times = c(1, 3, 5))
rbind(one_minus_KM = 1 - km_all$surv,
aalen_johansen = summary(aj, times = c(1,3,5))$pstate[, 2]) |> round(4)
## [,1] [,2] [,3]
## one_minus_KM 0.1432 0.4384 0.6526
## aalen_johansen 0.1355 0.3819 0.5417
At five years one-minus-KM says 65.3% of patients have died and Aalen–Johansen says 54.2%. Eleven percentage points apart. The usual next sentence is “so one-minus-KM is biased upward.” That sentence is wrong, and because we simulated the data we can show exactly what each estimator is doing. Run the same generator at two million patients with no censoring at all, and compute both targets directly:
truth <- function(n = 2e6, seed = 99) {
set.seed(seed)
age <- round(rnorm(n, 68, 8)); age <- pmin(pmax(age, 45), 88)
sex <- sample(c("male","female"), n, TRUE, c(.72,.28))
fvc <- round(rnorm(n, 72, 14)); fvc <- pmin(pmax(fvc, 35), 115)
dlco <- round(0.55*fvc + rnorm(n, 18, 9)); dlco <- pmin(pmax(dlco, 20), 100)
af <- rbinom(n, 1, plogis(-0.3 + 0.040*(fvc - 72)))
lp <- 0.045*(age-68) - 0.030*(fvc-72) - 0.012*(dlco-45) - 0.35*af +
0.25*(sex == "male")
t_death <- rweibull(n, 1.4, 4.2*exp(-lp/1.4))
t_tx <- ifelse(age < 68, rweibull(n, 1.1, 5.0*exp(0.055*(fvc-72)/1.1)), Inf)
tg <- c(1, 3, 5)
tibble(
t = tg,
# what ACTUALLY happens: died, and died before any transplant
cif_death = sapply(tg, function(x) mean(t_death <= x & t_death < t_tx)),
# the hypothetical world where transplant does not exist
marginal_death = sapply(tg, function(x) mean(t_death <= x)))
}
tr <- truth()
tr |> mutate(across(-t, ~ round(.x, 4)))
## # A tibble: 3 × 3
## t cif_death marginal_death
## <dbl> <dbl> <dbl>
## 1 1 0.128 0.135
## 2 3 0.392 0.45
## 3 5 0.548 0.663
Both estimators are right. One-minus-KM (0.653 at 5 years) is estimating the marginal distribution of the latent death time – 0.663 – the probability of dying by 5 years in a world where transplant could not happen. Aalen–Johansen (0.542) is estimating the actual probability of dying by 5 years with transplantation available – 0.548. Each lands within a percentage point of its own target:
km1 <- survfit(Surv(time, dead) ~ 1, data = d)
cmp <- bind_rows(
tibble(est = "1 - Kaplan-Meier", time = c(0, km1$time), p = c(0, 1 - km1$surv)),
tibble(est = "Aalen-Johansen CIF", time = c(0, aj$time),
p = c(0, aj$pstate[, 2])))
pts <- bind_rows(
tibble(est = "1 - Kaplan-Meier", time = tr$t, p = tr$marginal_death),
tibble(est = "Aalen-Johansen CIF", time = tr$t, p = tr$cif_death))
ggplot(cmp, aes(time, p, colour = est)) +
geom_step(linewidth = 1) +
geom_point(data = pts, size = 3.4, shape = 21, fill = "white",
stroke = 1.3, show.legend = FALSE) +
scale_colour_manual(values = unname(pal[c("orange", "blue")]), name = NULL) +
scale_y_continuous(limits = c(0, 0.75), labels = scales::percent) +
labs(title = "Two estimators, two different targets, both unbiased",
subtitle = paste("Open circles are the truth from a 2,000,000-patient",
"simulation: the marginal death distribution (orange)",
"\nand the actual cumulative incidence of death (blue)"),
x = "years since diagnosis", y = "probability of death by t") +
theme(legend.position = "bottom")

So the choice is not statistical, it is clinical. If you are counselling a patient on what is likely to happen to them, you want the cumulative incidence: transplants exist. If you are studying the biology of untreated fibrosis, the marginal quantity is the one you mean – but it is only estimable under the assumption that latent death and transplant times are independent, which is true in my generator by construction and is untestable in your data. That untestability is the real reason to default to Aalen–Johansen.
The most useful display is usually all states at once, which must sum to 1:
st <- as_tibble(aj$pstate) |>
setNames(c("alive", "dead", "transplanted")) |>
mutate(time = aj$time) |>
# survfit has no t = 0 row, and without it the area starts at the first event
add_row(alive = 1, dead = 0, transplanted = 0, time = 0, .before = 1) |>
pivot_longer(-time, names_to = "state", values_to = "p") |>
mutate(state = factor(state, levels = c("dead", "transplanted", "alive")))
ggplot(st, aes(time, p, fill = state)) +
geom_area() +
scale_fill_manual(values = unname(pal[c("orange", "violet", "cyan")]),
name = NULL) +
scale_y_continuous(labels = scales::percent, expand = c(0, 0)) +
scale_x_continuous(expand = c(0, 0)) +
labs(title = "Where the cohort is at any time",
subtitle = sprintf(
"At 5 years: %.0f%% dead, %.0f%% transplanted, %.0f%% alive with disease",
100*summary(aj, times=5)$pstate[2], 100*summary(aj, times=5)$pstate[3],
100*summary(aj, times=5)$pstate[1]),
x = "years since diagnosis", y = NULL)

For regression with competing risks there are two families, answering the two questions again. Cause-specific Cox models treat the competing event as censoring and describe the rate among those still at risk – fit one per cause:
d$tx <- as.numeric(d$status == 2)
cs <- rbind(
death = summary(coxph(Surv(time, dead) ~ antifib + age + fvc, data = d))$coef[, c(2, 5)],
transplant = summary(coxph(Surv(time, tx) ~ antifib + age + fvc, data = d))$coef[, c(2, 5)])
round(cs, 4)
## exp(coef) Pr(>|z|)
## antifibyes 0.6810 0.0098
## age 1.0476 0.0000
## fvc 0.9648 0.0000
## antifibyes 0.8210 0.4406
## age 0.9056 0.0000
## fvc 0.9620 0.0000
Read as six numbers: the antifibrotic lowers the death rate (HR NA) and does nothing to the transplant rate, correctly – it has no transplant effect in the generator. Age raises the death rate and sharply lowers the transplant rate, which is the age-68 eligibility rule showing up as a hazard ratio of 0.91 per year.
The other family, Fine–Gray subdistribution models, puts covariates directly on the cumulative incidence, so coefficients describe the curve you would plot. Both are legitimate; a covariate can perfectly well raise the cause-specific hazard of death while lowering the cumulative incidence, if it also raises the competing hazard enough. Reporting one and interpreting it as the other is the common error.
Immortal time
One last trap, and the costliest in observational work. To get a treatment, you must be alive when it is given. Classifying patients by whether they ever received it, and then following them from diagnosis, grants the treated group a stretch of guaranteed survival – immortal time.
Here is a drug with exactly zero effect on survival:
set.seed(55); n <- 600
t_death <- rweibull(n, 1.3, 3.5) # truth: treatment has NO effect at all
t_start <- rweibull(n, 1.0, 2.0) # when the drug happens to get started
t_cens <- pmin(rexp(n, 1/15), 6)
im <- tibble(id = 1:n,
time = pmin(t_death, t_cens),
dead = as.numeric(t_death <= t_cens)) |>
mutate(ever_treated = as.numeric(t_start < time),
start = ifelse(ever_treated == 1, t_start, NA_real_))
naive <- coxph(Surv(time, dead) ~ ever_treated, data = im)
c(HR = exp(coef(naive)), exp(confint(naive)), p = summary(naive)$coef[1, 5])
## HR.ever_treated p
## 2.862514e-01 2.333659e-01 3.511219e-01 3.442611e-33
A hazard ratio of 0.286 – an apparent 71% reduction in mortality, with \(p = 3e-33\) – from a drug that does nothing. The two fixes:
# (1) LANDMARK: pick a time, keep survivors, classify by exposure BY then
lmk <- 0.5
keep <- im$time > lmk
land <- coxph(Surv(time - lmk, dead) ~ treated_by_lmk,
data = im[keep, ] |>
mutate(treated_by_lmk = as.numeric(!is.na(start) &
start <= lmk)))
# (2) TIME-DEPENDENT: split each patient's follow-up at the day they start
td <- tmerge(as.data.frame(im[c("id","time","dead")]),
as.data.frame(im[c("id","time","dead")]),
id = id, death = event(time, dead))
td <- tmerge(td, as.data.frame(filter(im, ever_treated == 1)[c("id","start")]),
id = id, on_drug = tdc(start))
td$on_drug[is.na(td$on_drug)] <- 0
tdep <- coxph(Surv(tstart, tstop, death) ~ on_drug, data = td)
rbind(naive = c(exp(coef(naive)), exp(confint(naive))),
landmark_6_months = c(exp(coef(land)), exp(confint(land))),
time_dependent = c(exp(coef(tdep)), exp(confint(tdep)))) |>
`colnames<-`(c("HR", "lower", "upper")) |> round(3)
## HR lower upper
## naive 0.286 0.233 0.351
## landmark_6_months 1.178 0.921 1.508
## time_dependent 1.196 0.956 1.497
Both corrections cover the true value of 1. One dataset proves nothing, so repeat it 200 times:
one_rep <- function(seed, n = 600) {
set.seed(seed)
t_death <- rweibull(n, 1.3, 3.5); t_start <- rweibull(n, 1.0, 2.0)
t_cens <- pmin(rexp(n, 1/15), 6)
time <- pmin(t_death, t_cens); dead <- as.numeric(t_death <= t_cens)
ever <- as.numeric(t_start < time); st <- ifelse(ever == 1, t_start, NA)
id <- seq_len(n); base <- data.frame(id, time, dead)
lmk <- 0.5; keep <- time > lmk
b <- tmerge(base, base, id = id, death = event(time, dead))
b <- tmerge(b, data.frame(id = id[ever == 1], st = st[ever == 1]),
id = id, on_drug = tdc(st))
b$on_drug[is.na(b$on_drug)] <- 0
c(naive = coef(coxph(Surv(time, dead) ~ ever)),
landmark = coef(coxph(Surv(time[keep] - lmk, dead[keep]) ~
as.numeric(!is.na(st) & st <= lmk)[keep])),
tdep = coef(coxph(Surv(tstart, tstop, death) ~ on_drug, data = b)))
}
reps <- t(sapply(1:200, one_rep))
exp(colMeans(reps)) |> setNames(c("naive", "landmark", "time-dependent")) |>
round(3)
## naive landmark time-dependent
## 0.295 1.022 0.993
Mean hazard ratio over 200 replications: the naive analysis sits at 0.295, nowhere near the truth, while the landmark and time-dependent analyses give 1.022 and 0.993. The bias is not sampling noise; it is built into the question.
f_naive <- survfit(Surv(time, dead) ~ ever_treated, data = im)
im_l <- im[keep, ] |> mutate(g = as.numeric(!is.na(start) & start <= lmk))
f_land <- survfit(Surv(time - lmk, dead) ~ g, data = im_l)
lab <- c("0" = "never treated", "1" = "treated")
panels <- c("Naive: ever-treated, followed from diagnosis",
"Landmark: survivors at 6 months, clock restarted")
pp <- bind_rows(
tidy_km(f_naive) |> mutate(panel = panels[1]),
tidy_km(f_land) |> mutate(panel = panels[2])) |>
# alphabetical order would put "Landmark" first and contradict the subtitle
mutate(panel = factor(panel, levels = panels))
ggplot(pp, aes(time, surv, colour = lab[group])) +
geom_step(linewidth = 1) +
facet_wrap(~ panel) +
scale_colour_manual(values = unname(pal[c("grey", "green")]), name = NULL) +
scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
labs(title = "The same drug, which does nothing, analysed two ways",
subtitle = "Left: immortal time manufactures a large survival benefit",
x = "years since time zero", y = "survival") +
theme(legend.position = "bottom")

The left panel is a figure you have seen in print. The gap is entirely an artefact of the fact that dying early makes you ineligible for treatment.
The landmark approach is simple and transparent but discards early
events and misclassifies anyone treated after the landmark. The
time-dependent approach uses everything, at the cost of restructuring
the data into intervals – which is what tmerge is for, and
is worth learning properly. Neither fixes confounding; they fix only the
time alignment.
What to remember
Censoring is an assumption, not just a data structure. Everything here assumes a censored patient’s future resembles that of comparable patients still under observation. Nothing in the output checks it.
Know which of the three functions you are looking at. \(S\), \(h\) and \(H\) are interchangeable, but intuition about disease lives in the hazard’s shape, and curves that look similar can have radically different hazards.
Never show a survival curve without a risk table. The right tail is estimated from a handful of patients and the steps there are large and noisy.
Plot before you test. The log-rank test is an average over follow-up time and goes silent when curves cross – precisely when the difference matters most. Report landmark survival and RMST, with intervals, and demote the p-value.
RMST deserves more use than it gets. Area under the curve to a stated horizon, in years of life, always defined, no proportional hazards needed.
Use the bootstrap where it earns its keep. Not for a landmark difference with hundreds of events, where Greenwood is fine – for medians, differences of RMST, and anything else without a variance formula. Watch for failed replicates.
Decide whether your competing event is censoring or an event. If it removes patients from the possibility of the outcome, it is not censoring. One minus Kaplan–Meier is not wrong arithmetic; it answers a hypothetical question about a world where the competing event cannot happen, and that question needs an independence assumption you cannot check.
Check for immortal time in any exposure that happens after time zero. If being alive is a prerequisite for being classified as treated, the naive analysis will show a benefit whether or not one exists.