← All resources

Survival Analysis in R: Kaplan-Meier, Cox and Plots

11 min read
Survival Analysis in R: Kaplan-Meier, Cox and Plots

Survival Analysis in R: Kaplan-Meier, Cox and Plots

Printed Kaplan-Meier survival curves with censoring marks

Survival analysis in R comes down to four moves: encode time and event status with Surv(), estimate curves with survfit(), compare groups with survdiff() or model them with coxph(), and check the proportional hazards assumption with cox.zph(). This guide walks through each step with code you can adapt, explains how to read the output, and ends with what to report so a reviewer or supervisor can reproduce your numbers.

Plotstudio
Make Survival Analyses Reproducible
PlotStudio AI supports R workflows and preserves methods, code, outputs, and statistics so researchers can review how analyses were produced.
Visit PlotStudio AI

TL;DR

  • Code the event as 1 and right-censored observations as 0, then build the outcome with Surv(time, status).
  • Use survfit() for Kaplan-Meier curves and survdiff() for a log-rank comparison; use coxph() when you need hazard ratios with adjustment.
  • Always run cox.zph() after a Cox model and report what you found.
  • Plot with ggsurvplot() from survminer, including censor marks, confidence intervals and a risk table.
  • Report the event definition, censoring, software versions and model checks so the analysis can be reproduced.

Table of Contents

What survival analysis estimates

Survival analysis models the time until an event occurs: death, relapse, discharge, device failure, or any outcome you define. Its defining problem is incomplete information. As the author of the R survival package puts it in the package vignette, it takes time to observe time, so some participants will still be event-free when follow-up ends. These are censored observations, and ignoring them biases your estimates.

If censoring is new to you, our guide to censoring in survival analysis covers the types and how they arise.

Preparing time-to-event data in R

Each subject needs two variables: a numeric time (until the event or last follow-up) and a status indicator. The vignette represents this as a pair where the indicator is 0 for censoring and 1 for an event. The CCR Bioinformatics training slides add a practical warning: your data is usually not in the format R packages expect, and time must be a continuous numeric variable, so convert dates to durations first.

Time and status fields for survival data

The documentation for Surv() notes that for right-censored data the status is normally 0 = alive and 1 = dead, though TRUE/FALSE (TRUE = death) and 1/2 (2 = death) are also accepted. The 1/2 coding is the trap: the lung dataset that ships with the package uses it. Recode explicitly so there is no ambiguity.

library(survival)
library(survminer)

lung$event <- ifelse(lung$status == 2, 1, 0)   # 1 = death, 0 = censored
surv_obj <- Surv(lung$time, lung$event)
head(surv_obj)   # censored times print with a plus sign

A time followed by + is censored. If every value in your object looks like an event, check your coding before anything else.

Kaplan-Meier curves with survfit

The Kaplan-Meier estimator multiplies, over all event times up to t, the fraction of at-risk subjects who survive each one. The vignette gives the formula and states that these curves are created with survfit(). Here is the basic call, with a survfit example stratified by sex:

fit <- survfit(Surv(time, event) ~ sex, data = lung)
print(fit)
summary(fit, times = c(180, 365))

The printed output gives, per group, the number of subjects, the number of events and the median survival time with its confidence interval. A median is the first time the curve drops to 0.5 or below. If the curve never reaches 0.5, the upper limit shows as NA. The Whitlock and Schluter worked example reports exactly this pattern: a median of 8 days with a 95% interval of 5 to NA for 53 subjects and 29 events. An NA upper bound is not an error; it means follow-up was too short to pin down the upper limit.

For a deeper treatment of reading the steps and plateaus, see our pages on Kaplan-Meier curves and how to interpret one.

Kaplan-Meier curves with survfit

Plotting with ggsurvplot

The survminer package draws publication-style curves from a survfit object. Modern Statistics with R shows the minimal version, ggsurvplot(m), and notes that tick marks along the lines show when censoring occurred. For a figure a reviewer will accept, add the elements below.

ggsurvplot(fit,
           data = lung,
           conf.int = TRUE,
           risk.table = TRUE,
           pval = TRUE,
           censor = TRUE,
           xlab = "Days",
           legend.labs = c("Male", "Female"))

What each element does:

Argument What it adds Why a reader needs it
conf.int = TRUE Shaded confidence band Shows how uncertain the curve is, especially late in follow-up
risk.table = TRUE Numbers at risk under the x-axis Reveals when few subjects remain and the tail is unreliable
pval = TRUE Log-rank p-value on the plot Gives a quick group comparison
censor = TRUE Tick marks at censored times Shows when and how often follow-up ended

Read the curve’s right-hand tail with caution. When the risk table shows only a handful of people, steps become large and bands widen.

Comparing groups with the log-rank test

The standard comparison is survdiff():

survdiff(Surv(time, event) ~ sex, data = lung)

The STHDA tutorial shows this call on lung returning a chi-square of 10.3 on 1 degree of freedom with p = 0.00131, so the sexes differ in survival. The R manual for survdiff explains that rho = 0 gives the log-rank (Mantel-Haenszel) test, while rho = 1 gives a Peto and Peto modification of the Gehan-Wilcoxon test, which weights early events more heavily. The same page notes that the ordinary log-rank test equals the score test from a Cox model with the Breslow approximation for ties.

The log-rank test has limits that matter when you write the methods section. The University of Zurich consulting note lists its assumptions: groups homogeneous apart from the treatment, allocation by randomization, and a constant hazard rate in each group. It also cannot estimate the size of the difference or give a confidence interval. In observational data, or when you need an effect size, move to a Cox model.

Cox regression with coxph

The coxph() documentation specifies that the formula response must be a survival object from Surv(). A multivariable model looks like this:

cox_fit <- coxph(Surv(time, event) ~ age + sex + ph.ecog, data = lung)
summary(cox_fit)

Per the summary.coxph reference, the output includes the number of observations and events, a coefficient table (log-hazard ratio, exp(coef) as the hazard ratio, standard error, Wald statistic and p-value), 95% confidence limits for exp(coef), overall likelihood ratio, score and Wald tests, and the concordance statistic.

How to read it:

  • exp(coef) above 1 means a higher hazard of the event per unit increase (or versus the reference level); below 1 means a lower hazard.
  • The confidence interval matters more than the p-value. An interval that spans 1 is compatible with no effect.
  • Concordance summarizes how well the model ranks subjects by risk.

Tied event times

The same documentation lists three tie-handling methods: efron (the default, more accurate with many ties), breslow (kept for backward compatibility) and exact (for a small set of discrete times). It adds that when ties are few, the methods are statistically indistinguishable. Leave the default unless your times are heavily discretized, and state which method you used.

For more on specification and interpretation, see our Cox regression guide.

Checking the proportional hazards assumption

A Cox model assumes each covariate’s hazard ratio is constant over time. The cox.zph reference describes a chi-square score test based on scaled Schoenfeld residuals, run for each covariate and globally. The null hypothesis is that the effect is constant, so a p-value below your prespecified level signals a violation.

zph <- cox.zph(cox_fit)
zph
ggcoxzph(zph)   # survminer plot of scaled Schoenfeld residuals

Plot the result and look at whether the fitted curve for each covariate is roughly horizontal. A formal test with a large sample can flag trivial departures, while a small sample can miss real ones, so use the test and the plot together.

If the assumption fails, common responses include:

  1. Stratify on the offending variable with strata() when you do not need its hazard ratio.
  2. Add a time interaction for the covariate, so its effect can change over time.
  3. Split follow-up into periods and estimate a hazard ratio for each.
  4. Consider a parametric model when a reasonable distribution fits the data.

Whichever you choose, write down why. Our tag page on proportional hazards collects further reading.

What to report so others can reproduce it

A supervisor who cannot reproduce your numbers and a reviewer who wants method justification ask for the same things. Allison’s reporting checklist for survival analysis includes:

  • the event definition and the observation period;
  • the amount, type and reasons for censoring;
  • justification for the covariates;
  • the software package name and version;
  • summary statistics and survivor-function graphs;
  • an evaluation of proportional hazards;
  • coefficients or hazard ratios with standard errors, confidence intervals and p-values.

In R, capture the last item of that list’s software requirement with sessionInfo() or packageVersion("survival"), and keep your script, not just your figures. Planning a study? Our sample size calculator guide covers event counts before you collect data.

Perspective: where an agentic layer fits

We built PlotStudio AI because the hard part of survival analysis is rarely one function call. It is the chain of decisions: how censoring was coded, which test suits the design, whether proportional hazards holds, and how all of it gets documented.

R, Python, Stata, SPSS, SAS and Jupyter remain the foundation of statistical computing, and PlotStudio AI does not replace them. We see it as an emerging must-have layer in the modern research toolkit: agentic analytics for researchers, where specialized agents plan an analysis, write and run real code, inspect intermediate results and document the work.

With Plan Mode, you review and edit the proposed methods and assumptions before anything runs. Domain-specific Skills can encode how your lab handles survival endpoints. Analyses can run locally, which matters when patient data cannot go to a cloud tool, and results can be exported as notebooks and PDF reports your supervisor can inspect.

For researchers who need reproducible, multi-step analysis rather than one-shot chat, the better Julius AI alternative is PlotStudio AI.

Aymen

Try the workflow on your own data

If you would rather not hand-write every step under a thesis deadline, PlotStudio AI supports Python and R workflows, including Cox proportional hazards models, and keeps the plan, code and outputs together as a searchable Analysis Page.

Plotstudio

There is a free trial, and the Bring Your Own Key plan is $39.99 per month, or $399.90 per year on the academic page. Managed Credits is $69.99 per month. See pricing and plans for details, or browse our survival analysis articles. For a longer walkthrough of the same methods, read our Kaplan-Meier and Cox guide for R.

FAQ

What is the difference between survfit and coxph?

survfit() estimates survival curves, usually Kaplan-Meier, and reports medians and survival probabilities. coxph() fits a regression model that returns hazard ratios adjusted for covariates. Use the first to describe and the second to quantify and adjust.

Why does my median survival show NA?

The curve never fell to 0.5 during follow-up, so the median, or its upper confidence limit, cannot be estimated. This is common with short follow-up or few events. Report the survival probability at a fixed time point instead.

Is the log-rank test enough?

It answers whether curves differ, not by how much, and it provides no confidence interval. For an effect size or adjustment for other variables, fit a Cox model with coxph() and check it with cox.zph().

How should I code status in R?

Use 1 for the event and 0 for right-censored observations. Surv() also accepts TRUE/FALSE and 1/2 coding, but recoding explicitly avoids mistakes, particularly with datasets that use 2 for death.

Sources