LSMA

LONDON SCHOOL OF MULTIOMICS & AI

LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 31 lessons

Survival analysis

Survival analysis

Survival analysis

How long do patients live, and what changes it? This lesson handles censored follow-up correctly, draws Kaplan–Meier curves with ggplot2, and fits a Cox model to advanced lung cancer data.

This lesson follows Random forests and cross-validation, where you predicted a label and checked the prediction honestly.

Time to an event, and censoring

Many clinical questions are about time: how long patients live after diagnosis, how long until a tumour returns. Such an outcome has two parts, a length of time and whether the event happened. The difficulty is that a study ends, or patients leave it, before everyone has had the event. A patient followed for 400 days and still alive at the last contact is censored at 400 days: you know they survived at least that long, but not how much longer.

Censored patients cannot simply be dropped, and their follow-up time cannot be treated as a time of death. Dropping them throws away the information that they lived at least that long, and makes survival look worse. Treating their last contact as death does the same. Survival analysis is the set of methods that use both kinds of record correctly. It is common in omics studies too, wherever a gene signature is linked to patient outcome.

The data, lung from the survival package, which ships with R, follow 228 patients with advanced lung cancer from the North Central Cancer Treatment Group. time is the follow-up in days, and status records what happened at the end of it, coded 1 for censored and 2 for died. That 1/2 coding is unusual, so the first step is a clear 0/1 event column.

R
library(survival)
library(ggplot2)

lung <- survival::lung
lung$event <- as.integer(lung$status == 2)        # 1 = died, 0 = censored
lung$sex   <- factor(lung$sex, levels = c(1, 2), labels = c("male", "female"))

table(lung$event)
head(Surv(lung$time, lung$event), 10)
0 1 63 165 [1] 306 455 1010+ 210 883 1022+ 310 361 218 166

What this does

  • lung$status == 2 is TRUE for patients who died, and as.integer() turns that into 1 and 0. 165 patients died during follow-up and 63 were censored.
  • factor(lung$sex, ...) replaces the codes 1 and 2 with readable labels, as in Matrices, lists and factors. The first level, male, becomes the reference group in the models below.
  • Surv(time, event) builds a survival object, the outcome every survival function expects. Printed, it shows each time with a + after censored ones: patient 3 was alive at 1,010 days, while patient 1 died at 306.

A quick look shows why ignoring censoring misleads. The median follow-up time of the patients who died is 226 days, and the median of all follow-up times is 255.5 days. Neither is the median survival. The first ignores the censored patients, who tended to be followed for longer; the second treats censoring as an event. The method below gives 310 days.

The methods in this lesson assume that censoring is non-informative: a patient who is censored has the same outlook as patients still being followed at that time. That holds when follow-up simply ends because the study closes. It fails if, for example, the sickest patients stop attending clinic, and no analysis can fully repair that. Always ask why patients were censored.

Kaplan–Meier curves

The Kaplan–Meier estimator estimates the probability of surviving beyond each time. It moves forward through the event times. At each one, it multiplies the survival so far by the fraction of patients at risk (still followed and alive just before that time) who did not die then. Censored patients count as at risk until they are censored, then leave quietly without causing a step.

R
km_all <- survfit(Surv(time, event) ~ 1, data = lung)
km_all
summary(km_all, times = c(180, 365, 730))
n events median 0.95LCL 0.95UCL [1,] 228 165 310 285 363 … time n.risk n.event survival std.err lower 95% CI upper 95% CI 180 160 63 0.722 0.0298 0.6655 0.783 365 65 58 0.409 0.0358 0.3447 0.486 730 13 38 0.116 0.0283 0.0716 0.187

Reading the output

  • ~ 1 means one curve for everyone. The median survival is the time at which the estimated curve falls to 50%: 310 days, with a 95% confidence interval of 285 to 363 days.
  • summary(..., times = ...) reads the curve at chosen times. Estimated survival is 72.2% at 180 days, 40.9% at one year (95% CI 34.5% to 48.6%) and 11.6% at two years.
  • n.risk is how many patients were still at risk at that time; n.event counts the deaths since the previous time shown, so 63 by day 180, then 58 more by day 365.

Watch the numbers at risk. By two years only 13 patients remain, so the right-hand end of any curve rests on very few people, and its confidence interval is wide. A curve that ends in a long flat stretch usually means a handful of censored patients, not a cure.

Worked example · the first two steps by hand

day 5: 228 at risk, 1 death → 227 ÷ 228 = 0.9956
day 11: 227 at risk, 3 deaths → 0.9956 × 224 ÷ 227 = 0.9825
day 12: 224 at risk, 1 death → 0.9825 × 223 ÷ 224 = 0.9781

Step by step. The shortest follow-up is 5 days, a death, so 227 of the 228 patients survive that step. On day 11, three of the 227 still at risk die, so the fraction surviving the step is 224 ÷ 227, multiplied by what came before. summary(km_all) prints exactly these values. A censored patient would reduce the number at risk at the next step without multiplying the survival down.

What the answer means. Each step's size depends on how many remain at risk. Early on, one death moves the curve by less than half a percentage point; at two years, with 13 at risk, one death moves it by almost a twelfth of its height.

Comparing groups: plot and log-rank test

Adding a variable to the formula, ~ sex, gives one curve per group. survminer is a popular package for plotting these, but you do not need it: the fitted object holds everything a ggplot2 figure needs, and building the data frame yourself shows what is drawn.

R
km_sex <- survfit(Surv(time, event) ~ sex, data = lung)
km_sex

km_df <- data.frame(
  time   = km_sex$time,
  surv   = km_sex$surv,
  lower  = km_sex$lower,
  upper  = km_sex$upper,
  censor = km_sex$n.censor > 0,
  sex    = sub("sex=", "", rep(names(km_sex$strata), times = km_sex$strata))
)
start <- data.frame(time = 0, surv = 1, lower = 1, upper = 1, censor = FALSE,
                    sex = c("male", "female"))
km_df <- rbind(start, km_df)
km_df$sex <- factor(km_df$sex, levels = c("male", "female"))

ggplot(km_df, aes(time, surv, colour = sex)) +
  geom_step(linewidth = 0.9) +
  geom_point(data = subset(km_df, censor), shape = 3, size = 2) +
  scale_colour_manual(values = c(male = "#0072B2", female = "#D55E00")) +
  scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
  labs(x = "Days", y = "Estimated survival", colour = NULL) +
  theme_classic(base_size = 13)

survdiff(Surv(time, event) ~ sex, data = lung)
n events median 0.95LCL 0.95UCL sex=male 138 112 270 212 310 sex=female 90 53 426 348 550 … N Observed Expected (O-E)^2/E (O-E)^2/V sex=male 138 112 91.6 4.55 10.3 sex=female 90 53 73.4 5.68 10.3 Chisq= 10.3 on 1 degrees of freedom, p= 0.001

What this does

  • km_sex$time, surv, lower and upper hold every step of both curves, one after the other. km_sex$strata says how many rows belong to each group (119 for men, 87 for women), so rep() labels them and sub() trims the "sex=" prefix.
  • The curves must start at 100% on day 0, which the fitted object does not store, so start adds those two rows.
  • geom_step() draws the staircase: survival stays flat between events and drops at each one. A smooth line would invent changes between deaths.
  • geom_point(..., shape = 3) marks censoring times with small crosses, the usual convention. The lower and upper columns are there if you want to add the confidence bands with a stepped ribbon.

Median survival is 270 days for men and 426 days for women, and at one year 33.6% of men and 52.7% of women are estimated to be alive. The log-rank test asks whether the curves differ anywhere over follow-up. At each death time it compares the deaths seen in each group with those expected if the groups shared one curve, then adds up over time. Men had 112 deaths against 91.6 expected, women 53 against 73.4; the chi-squared statistic is 10.3 on 1 degree of freedom, p = 0.001.

A good published KM figure also shows the numbers at risk beneath the axis at a few times. summary(km_sex, times = c(0, 250, 500, 750, 1000))$n.risk gives them: 138, 62, 20, 7 and 2 men, and 90, 53, 21 and 3 women (no woman is followed to 1,000 days). Readers need these to judge how much the right-hand end of each curve can be trusted.

Cox models and hazard ratios

The log-rank test gives a p-value but no effect size, and cannot adjust for other variables. The Cox proportional hazards model does both. The hazard is the instantaneous rate of the event among those still at risk: roughly, the chance of dying in the next short interval for someone alive now. The Cox model assumes each variable multiplies the hazard by a fixed factor, the hazard ratio (HR), at every time point, without saying anything about the shape of the baseline hazard itself.

R
cox <- coxph(Surv(time, event) ~ sex + age + ph.ecog, data = lung)
summary(cox)
round(cbind(HR = exp(coef(cox)), exp(confint(cox))), 2)
n= 227, number of events= 164 (1 observation deleted due to missingness) coef exp(coef) se(coef) z Pr(>|z|) sexfemale -0.552612 0.575445 0.167739 -3.294 0.000986 *** age 0.011067 1.011128 0.009267 1.194 0.232416 ph.ecog 0.463728 1.589991 0.113577 4.083 4.45e-05 *** … Concordance= 0.637 (se = 0.025 ) … HR 2.5 % 97.5 % sexfemale 0.58 0.41 0.80 age 1.01 0.99 1.03 ph.ecog 1.59 1.27 1.99

Reading the output

  • coef is the log hazard ratio; exp(coef) is the hazard ratio itself. As with odds ratios in Counts and proportions, confidence intervals are computed on the log scale and then exponentiated, which is what exp(confint(cox)) does.
  • sexfemale, HR 0.58 (95% CI 0.41 to 0.80). At any time during follow-up, women had a hazard of death about 42% lower than men of the same age and performance score. Fitting sex alone gives HR 0.59 (0.42 to 0.82), so adjustment barely changes it.
  • age, HR 1.01 per year (0.99 to 1.03), p = 0.23. For a 10-year difference that is 1.01110, about 1.12, but the interval includes 1: these data do not show a clear age effect once sex and performance score are accounted for.
  • ph.ecog, HR 1.59 per point (1.27 to 1.99). ECOG performance status is a doctor's rating of how well a patient manages daily activities, from 0 (fully active) to 4 (bedbound). Each point higher is associated with a 59% higher hazard. Entering it as a number assumes every step has the same effect; only one patient scored 3, so that assumption cannot be checked well here.
  • One patient with a missing ECOG score was dropped, leaving 227 patients and 164 deaths. The concordance, 0.637, is the probability that of two patients, the one the model rates as higher risk dies first; 0.5 is chance.

A hazard ratio is not a ratio of survival times or of probabilities. HR 0.58 does not mean women live 1.7 times as long, nor that 42% fewer women die; everyone in this study eventually faces the same outcome if followed long enough. It describes the rate at each moment. The medians, 270 and 426 days, are the plainer way to describe the difference in time.

These are associations in an observational cohort. Sex is not a treatment, and the model cannot say why women fared better; other differences between the groups, not recorded here, may explain part of it.

R
zph <- cox.zph(cox)
zph
plot(zph)
chisq df p sex 2.305 1 0.13 age 0.188 1 0.66 ph.ecog 2.054 1 0.15 GLOBAL 4.464 3 0.22

Checking proportional hazards

The model's central assumption is that each hazard ratio stays the same over time. If women's advantage were large early and vanished later, a single HR of 0.58 would average over two different stories. cox.zph() tests this for each variable, using residuals that should show no trend with time when the assumption holds. Small p-values signal a problem. Here none is small (global p = 0.22), and plot(zph) draws each variable's estimated effect against time, which should be roughly flat.

A non-significant test is not proof, especially in a small study, so look at the plots and at the KM curves as well. Curves that cross are a warning sign. If the assumption clearly fails, common remedies are to stratify the model by that variable (strata(sex) in the formula) or to report hazard ratios for separate time periods.

Common mistakes

  • Using status as coded 1/2 without checking which value means the event. Surv() accepts 1/2, but reversing them silently analyses censoring as death.
  • Dropping censored patients, or comparing the mean follow-up times of groups.
  • Splitting a continuous measurement, such as a gene's expression, at a cut-off chosen because it gives the smallest log-rank p-value. That is multiple testing in disguise.
  • Reading the flat tail of a KM curve as a plateau when only a few patients remain at risk.
  • Calling a hazard ratio a relative risk, or reporting it without its confidence interval.
Go deeper: survival and high-dimensional data

With a handful of clinical variables, a Cox model like the one above is enough. With thousands of genes and a few hundred patients, an ordinary Cox model would overfit, just as a classifier would in Random forests and cross-validation. Penalised Cox models, such as those fitted by the glmnet package with family = "cox", shrink most coefficients to zero and keep a small panel of genes; random survival forests (the randomForestSRC package) extend random forests to censored outcomes.

The rules for honest checking carry over unchanged: choose genes inside cross-validation, keep a test set untouched, and judge the result with a measure suited to censored data, such as the concordance, rather than an accuracy.

The estimator is from Kaplan & Meier 1958, "Nonparametric estimation from incomplete observations" (Journal of the American Statistical Association), and the model from Cox 1972, "Regression models and life-tables" (Journal of the Royal Statistical Society, Series B). The test behind cox.zph() is from Grambsch & Therneau 1994 (Biometrika). The lung data come from Loprinzi et al. 1994 (Journal of Clinical Oncology). Clark et al. 2003, "Survival analysis part I: basic concepts and first analyses" (British Journal of Cancer), is a clear introduction written for clinicians.

Key point

Survival data have a time and an event, and censored patients carry information. Describe groups with Kaplan–Meier curves, medians and numbers at risk; compare them with the log-rank test; estimate adjusted effects with a Cox model, reported as hazard ratios with intervals; and check that the hazards really are proportional.

Further reading · Module 5Clark et al. 2003: survival analysis from first principles, with clinical examples. · All reading for this course

Check your understanding

1. A patient was last seen alive at 400 days, when the study ended. How should they enter the analysis?

2. A Cox model gives a hazard ratio of 0.58 (95% CI 0.41 to 0.80) for women compared with men. What does it mean?

3. What does cox.zph() check?

Ask LSMA