The Cox proportional hazards model, the Harrell way
Contents
- The hazard, and what “proportional” means
- The partial likelihood, by hand
- The data
- Spending degrees of freedom
- Fitting with
cph - Two measurements of one thing
- Effects: hazard ratios and partial effects
- Diagnostic 1: is the hazard really proportional?
- Diagnostic 2: functional form
- Predicted survival curves
- Validation and calibration
- Missing data, properly
- The nomogram
- What to remember
The hazard, and what “proportional” means
Survival modelling works with the hazard: the instantaneous rate of failure at time \(t\) among those still at risk,
\[h(t) = \lim_{\delta \to 0} \frac{P(t \le T < t + \delta \mid T \ge t)}{\delta}\]
Cox’s model says that covariates multiply the hazard by a constant factor that does not depend on time:
\[h(t \mid X) = h_0(t) \, \exp(X\beta)\]
Two things follow, and they are the whole reason the model is used.
First, \(h_0(t)\) – the baseline hazard, the part that varies with time – is left completely unspecified. You never have to claim that survival is Weibull, or exponential, or anything else. This is what makes Cox regression semiparametric.
Second, the ratio of hazards between any two patients is \(\exp\{(X_1 - X_2)\beta\}\), which is constant over time. That is the proportional hazards assumption, and it is an assumption, not a conclusion.
On the log scale it has a clean visual signature: two groups’ log-hazards are parallel curves. When they are not parallel – when the hazard ratio grows, shrinks or reverses – the model is fitting an average of something that is changing, and that average may describe nobody.
tg <- seq(1, 60, length.out = 400)
h0 <- function(t) 0.02 * (t / 20)^1.3
lay <- function(hA, hB, scenario) {
bind_rows(
tibble(t = tg, h = hA, group = "group A"),
tibble(t = tg, h = hB, group = "group B")) |>
mutate(scenario = scenario)
}
sc <- c("proportional hazards", "NOT proportional")
both <- bind_rows(
lay(h0(tg), 2.2 * h0(tg), sc[1]),
lay(h0(tg), h0(tg) * exp(1.6 - 0.06 * tg), sc[2])) |>
# without this the facets order alphabetically and NOT-proportional comes first
mutate(scenario = factor(scenario, levels = sc))
panels <- bind_rows(
both |> mutate(value = h, measure = "hazard h(t)"),
both |> mutate(value = log(h), measure = "log hazard log h(t)"))
ggplot(panels, aes(t, value, colour = group)) +
geom_line(linewidth = 1) +
facet_grid(measure ~ scenario, scales = "free_y", switch = "y") +
scale_colour_manual(values = unname(pal[c("blue", "orange")])) +
labs(title = "What the proportional hazards assumption looks like",
subtitle = "on the log scale, PH means parallel; the right-hand column crosses",
x = "time", y = NULL, colour = NULL) +
theme(legend.position = "top", strip.placement = "outside")

In the right-hand column the hazard ratio starts above 1 and ends below it: group B is worse early and better later. A Cox model fitted to that data will report one number somewhere in the middle, and it will be wrong at both ends. Section 8 is about catching this.
The partial likelihood, by hand
Cox’s insight was that \(\beta\) can be estimated without ever estimating \(h_0(t)\). The trick: at each moment when a death occurs, ask only which of the patients still at risk was the one who died. The baseline hazard is common to everyone in that risk set, so it cancels out of the ratio.
\[L(\beta) = \prod_{j \,:\, \text{events}} \frac{\exp(X_j\beta)}{\sum_{k \in R(t_j)} \exp(X_k\beta)}\]
where \(R(t_j)\) is the set of patients still alive and under observation just before time \(t_j\). This is a partial likelihood: it discards the information in the actual event times and keeps only their ordering.
Six patients make it concrete.
toy <- tibble(id = 1:6,
time = c(5, 8, 12, 15, 20, 25),
event = c(1, 1, 0, 1, 1, 0),
x = c(1, 0, 1, 1, 0, 0))
toy
## # A tibble: 6 × 4
## id time event x
## <int> <dbl> <dbl> <dbl>
## 1 1 5 1 1
## 2 2 8 1 0
## 3 3 12 0 1
## 4 4 15 1 1
## 5 5 20 1 0
## 6 6 25 0 0
ev <- toy$time[toy$event == 1]
ggplot(toy, aes(y = factor(id))) +
geom_vline(xintercept = ev, linetype = "dashed",
colour = pal[["grey"]], linewidth = 0.4) +
geom_segment(aes(x = 0, xend = time, yend = factor(id), colour = factor(x)),
linewidth = 1.2) +
geom_point(aes(x = time, colour = factor(x),
shape = ifelse(event == 1, "death", "censored")), size = 3.6) +
scale_shape_manual(values = c(death = 19, censored = 1), name = NULL) +
scale_colour_manual(values = unname(pal[c("blue", "orange")]),
labels = c("x = 0", "x = 1"), name = NULL) +
scale_x_continuous(breaks = c(0, ev, 25)) +
labs(title = "Six patients, four deaths",
subtitle = "each dashed line is an event time; everyone whose bar reaches it is in that risk set",
x = "time", y = "patient") +
theme(legend.position = "top")

Read the risk sets off the figure. At \(t=5\) everybody is still at risk, so the denominator runs over all six. At \(t=20\) only patients 5 and 6 remain.
log_pl <- function(b) {
total <- 0
for (tj in toy$time[toy$event == 1]) {
risk <- toy[toy$time >= tj, ] # still at risk at tj
xj <- toy$x[toy$time == tj & toy$event == 1] # who died
total <- total + b * xj - log(sum(exp(b * risk$x)))
}
total
}
by_hand <- optimize(log_pl, c(-5, 5), maximum = TRUE)
c(beta = by_hand$maximum, logPL = by_hand$objective)
## beta logPL
## 1.073068 -4.787279
cf <- coxph(Surv(time, event) ~ x, data = toy)
c(beta = unname(coef(cf)), logPL = cf$loglik[2])
## beta logPL
## 1.073068 -4.787279
Identical to six decimal places. Nothing is hidden inside
coxph beyond what those four fractions contain.
tibble(b = seq(-2.5, 4.5, length.out = 400)) |>
mutate(ll = vapply(b, log_pl, numeric(1))) |>
ggplot(aes(b, ll)) +
geom_line(colour = pal[["blue"]], linewidth = 1) +
geom_vline(xintercept = by_hand$maximum, linetype = "dashed",
colour = pal[["orange"]]) +
annotate("point", x = by_hand$maximum, y = by_hand$objective,
colour = pal[["orange"]], size = 3) +
labs(title = "The partial log-likelihood for these six patients",
subtitle = sprintf("maximised at beta = %.3f, a hazard ratio of %.2f",
by_hand$maximum, exp(by_hand$maximum)),
x = expression(beta), y = "partial log-likelihood")

The curve is flat-ish and the maximum shallow, which is what four events buys you. Everything in the rest of this post is about the same curve computed from 165 events and nine parameters.
The data
The NCCTG lung cancer cohort that ships with survival:
228 patients with advanced lung cancer, survival in days, plus
performance status and weight loss. Real data, real missingness.
data(cancer, package = "survival")
d <- as_tibble(lung) |>
transmute(time,
dead = status == 2, # 1 = censored, 2 = dead
age,
sex = factor(sex, 1:2, c("male", "female")),
ecog = ph.ecog, # 0 = asymptomatic ... 4 = bedbound
karno = ph.karno, # 100 = normal ... 0 = dead
wt_loss = wt.loss, # kg lost in last 6 months
meal_cal = meal.cal)
c(patients = nrow(d), deaths = sum(d$dead),
median_followup_days = median(d$time))
## patients deaths median_followup_days
## 228.0 165.0 255.5
miss <- tibble(variable = names(d),
n_missing = colSums(is.na(d))) |>
filter(n_missing > 0) |>
mutate(pct = 100 * n_missing / nrow(d))
ggplot(miss, aes(n_missing, reorder(variable, n_missing))) +
geom_segment(aes(xend = 0, yend = reorder(variable, n_missing)),
colour = pal[["grey"]]) +
geom_point(colour = pal[["magenta"]], size = 4) +
geom_text(aes(label = sprintf("%d (%.0f%%)", n_missing, pct)),
hjust = -0.35, size = 3.4, colour = pal[["grey"]]) +
scale_x_continuous(expand = expansion(mult = c(0, 0.25))) +
labs(title = "Missing values in the lung cohort",
subtitle = sprintf("only %d of %d patients are complete on every variable",
sum(complete.cases(d)), nrow(d)),
x = "patients with a missing value", y = NULL)

Note meal.cal: 47 missing, over 20%. A complete-case
analysis including it would silently discard a fifth of the cohort. We
will leave it out of the model and come back to the general problem in
section 12.
One more thing to look at before modelling – how many distinct values each predictor actually takes. This decides how flexibly each can be fitted.
vapply(d[c("age", "ecog", "karno", "wt_loss")],
\(x) length(unique(na.omit(x))), integer(1))
## age ecog karno wt_loss
## 42 4 6 53
table(ecog = d$ecog, useNA = "ifany")
## ecog
## 0 1 2 3 <NA>
## 63 113 50 1 1
karno takes only 6 values (50 to 100 in steps of 10) and
ecog only 4, one of which has a single patient. Asking for
a 4-knot spline on a variable with 6 distinct values is asking for knots
the data cannot support – rcs will warn and then quietly
place fewer. Both belong in the model as linear terms.
Spending degrees of freedom
Harrell’s framing is that model complexity is a budget, and the currency is events, not patients. The rule of thumb in Regression Modeling Strategies is roughly 15 events per parameter before a model can be fitted without penalisation and still be expected to validate.
n_events <- sum(d$dead)
c(events = n_events,
budget_at_15_per_param = floor(n_events / 15))
## events budget_at_15_per_param
## 165 11
That allows about 11 parameters. The model below spends 9.
Just as important is what you must not spend the budget on. Stepwise selection, “univariable screening”, and dropping terms because \(p > 0.05\) all use the outcome to choose the model, and then report inference as though the model had been chosen in advance. The standard errors, p-values and confidence intervals that come out are all too small. The discipline is to decide the specification from subject knowledge and from the number of distinct values available – as above – and then fit it once.
Fitting with cph
cph is the rms version of
coxph. It fits the same model; what it adds is that the fit
object remembers enough about the data to support everything downstream
– anova, summary, Predict,
validate, calibrate, nomogram –
without you restating anything.
# rms stores only the NAME of the datadist object and looks it up in the
# global environment. knitr evaluates each chunk in its own environment, so
# inside an .Rmd this assignment is required.
dd <- datadist(d)
assign("dd", dd, envir = globalenv())
options(datadist = "dd")
f <- cph(Surv(time, dead) ~ rcs(age, 4) + sex + ecog + karno + rcs(wt_loss, 4),
data = d,
x = TRUE, y = TRUE, # keep design matrix and response: needed by
# validate(), calibrate(), cox.zph()
surv = TRUE, # keep baseline survival: needed for absolute
# risk predictions and the nomogram
time.inc = 365) # the horizon calibrate() will default to
f
## Frequencies of Missing Values Due to Each Variable
## Surv(time, dead) age sex ecog
## 0 0 0 1
## karno wt_loss
## 1 14
##
## Cox Proportional Hazards Model
##
## cph(formula = Surv(time, dead) ~ rcs(age, 4) + sex + ecog + karno +
## rcs(wt_loss, 4), data = d, x = TRUE, y = TRUE, surv = TRUE,
## time.inc = 365)
##
##
## Model Tests Discrimination
## Indexes
## Obs 213 LR chi2 36.99 R2 0.160
## Events 151 d.f. 9 R2(9,213)0.123
## Center 3.7448 Pr(> chi2) 0.0000 R2(9,151)0.169
## Score chi2 37.37 Dxy 0.298
## Pr(> chi2) 0.0000
##
## Coef S.E. Wald Z Pr(>|Z|)
## age 0.0392 0.0391 1.00 0.3159
## age' -0.0829 0.0772 -1.07 0.2834
## age'' 0.4942 0.3645 1.36 0.1751
## sex=female -0.6173 0.1796 -3.44 0.0006
## ecog 0.7281 0.1954 3.73 0.0002
## karno 0.0154 0.0098 1.57 0.1160
## wt_loss -0.0216 0.0311 -0.69 0.4876
## wt_loss' 0.1669 0.2323 0.72 0.4724
## wt_loss'' -0.3590 0.4639 -0.77 0.4389
c(parameters = f$stats[["d.f."]],
events = f$stats[["Events"]],
events_per_parameter = round(f$stats[["Events"]] / f$stats[["d.f."]], 1))
## parameters events events_per_parameter
## 9.0 151.0 16.8
Within budget. Now the Wald table, organised by predictor rather than
by coefficient – which is what you want once age and
wt_loss each occupy three columns of the design matrix.
a <- anova(f)
a
## Wald Statistics Response: Surv(time, dead)
##
## Factor Chi-Square d.f. P
## age 5.21 3 0.1571
## Nonlinear 2.61 2 0.2707
## sex 11.82 1 0.0006
## ecog 13.89 1 0.0002
## karno 2.47 1 0.1160
## wt_loss 2.62 3 0.4539
## Nonlinear 0.91 2 0.6335
## TOTAL NONLINEAR 3.56 4 0.4691
## TOTAL 36.33 9 <.0001
ad <- as.data.frame(unclass(a))
names(ad) <- c("chisq", "df", "p")
ad_plot <- ad |>
tibble::rownames_to_column("term") |>
filter(!term %in% c("TOTAL", "TOTAL NONLINEAR")) |>
mutate(nonlinear = grepl("Nonlinear", term),
label = ifelse(nonlinear, paste0(" nonlinear part"), trimws(term)),
label = make.unique(label),
stat = chisq - df)
ggplot(ad_plot, aes(stat, reorder(label, stat))) +
geom_vline(xintercept = 0, colour = pal[["grey"]], linewidth = 0.4) +
geom_segment(aes(xend = 0, yend = reorder(label, stat)),
colour = pal[["grey"]], linewidth = 0.5) +
geom_point(aes(colour = nonlinear), size = 4) +
scale_colour_manual(values = unname(pal[c("blue", "magenta")]), guide = "none") +
labs(title = "Relative predictive strength",
subtitle = expression(Wald~chi^2~minus~its~degrees~of~freedom),
x = NULL, y = NULL)

Subtracting the degrees of freedom makes a 3-df spline comparable
with a 1-df binary term: it is the chi-square penalised by what it cost.
sex and ecog carry the model. Every nonlinear
component lands at or below zero – the splines did not earn their keep
here.
That is worth stating carefully, because it is where a lot of applied practice goes wrong. The right conclusion is “the data do not show curvature”, not “the effects are linear”. Having spent the degrees of freedom to look, the honest move is to keep the splines in and let the confidence bands be as wide as they genuinely are. Refitting without them and reporting the narrower intervals would be exactly the selection problem of the previous section.
Two measurements of one thing
Look at karno in the model output: the coefficient is
positive. Taken at face value that says a
higher Karnofsky score – better performance status – predicts a
higher hazard, which is clinically backwards.
c(pearson = cor(d$ecog, d$karno, use = "complete.obs"),
spearman = cor(d$ecog, d$karno, method = "spearman", use = "complete.obs"))
## pearson spearman
## -0.8072667 -0.8183149
rbind("karno alone" = c(unname(coef(coxph(Surv(time, dead) ~ karno, data = d))), NA),
"karno + ecog" = unname(coef(coxph(Surv(time, dead) ~ karno + ecog, data = d)))) |>
`colnames<-`(c("karno", "ecog")) |>
round(5)
## karno ecog
## karno alone -0.01645 NA
## karno + ecog 0.00742 0.57367
Alone, karno behaves as expected: the coefficient is
negative, higher score means lower hazard. Add ecog – which
measures the same underlying construct, correlated at -0.81 – and the
sign flips.
d |> filter(!is.na(ecog), !is.na(karno)) |>
ggplot(aes(factor(ecog), karno)) +
geom_boxplot(fill = pal[["blue"]], alpha = 0.18,
colour = pal[["grey"]], outlier.shape = NA) +
geom_jitter(width = 0.18, height = 2, alpha = 0.35,
colour = pal[["blue"]]) +
labs(title = "ECOG and Karnofsky are two scales for the same thing",
subtitle = "the Cox model is asked to separate effects the data cannot separate",
x = "ECOG performance status", y = "Karnofsky score")

This is not a defect of the Cox model; it is what a partial effect means. The coefficient answers “what happens to the hazard when Karnofsky changes and ECOG is held fixed” – and the figure shows how few patients exist to answer that question. Harrell’s prescription is data reduction before modelling: combine collinear measurements into a single summary, or choose one on clinical grounds, rather than letting the fit arbitrate. Keeping both, as here, is defensible only if you report the pair jointly and refuse to interpret either coefficient on its own.
anova(f)["karno", , drop = FALSE]
## Chi-Square d.f. P
## karno 2.470347 1 0.1160123
Effects: hazard ratios and partial effects
summary.rms reports inter-quartile-range effects rather
than per-unit ones. For a spline a per-unit hazard ratio would be
meaningless – the slope differs everywhere – so the question becomes
“how much does the hazard change between a typical low and a typical
high value”.
summary(f)
## Effects Response : Surv(time, dead)
##
## Factor Low High Diff. Effect S.E. Lower 0.95 Upper 0.95
## age 56 69.00 13.00 -0.067786 0.23775 -0.533760 0.39819
## Hazard Ratio 56 69.00 13.00 0.934460 NA 0.586400 1.48910
## ecog 0 1.00 1.00 0.728130 0.19538 0.345200 1.11110
## Hazard Ratio 0 1.00 1.00 2.071200 NA 1.412300 3.03760
## karno 75 90.00 15.00 0.231160 0.14707 -0.057098 0.51942
## Hazard Ratio 75 90.00 15.00 1.260100 NA 0.944500 1.68110
## wt_loss 0 15.75 15.75 0.036881 0.21793 -0.390260 0.46402
## Hazard Ratio 0 15.75 15.75 1.037600 NA 0.676880 1.59050
## sex - female:male 1 2.00 NA -0.617330 0.17955 -0.969240 -0.26542
## Hazard Ratio 1 2.00 NA 0.539380 NA 0.379370 0.76688
sm <- unclass(summary(f))
keep <- which(sm[, "Type"] == 2) # the hazard-ratio rows
hr <- tibble(term = trimws(rownames(sm)[keep - 1]),
low = sm[keep, "Low"], high = sm[keep, "High"],
hr = sm[keep, "Effect"],
lo = sm[keep, "Lower 0.95"], hi = sm[keep, "Upper 0.95"]) |>
mutate(label = sprintf("%s (%g to %g)", term, low, high))
ggplot(hr, aes(hr, reorder(label, hr))) +
geom_vline(xintercept = 1, linetype = "dashed", colour = pal[["grey"]]) +
geom_pointrange(aes(xmin = lo, xmax = hi), colour = pal[["blue"]],
linewidth = 0.7, size = 0.6) +
scale_x_log10() +
labs(title = "Inter-quartile-range hazard ratios",
subtitle = "log scale, so a hazard ratio and its reciprocal sit equally far from 1",
x = "hazard ratio", y = NULL)

one <- function(v) {
as.data.frame(Predict(f, name = v)) |>
transmute(x = .data[[v]], yhat, lower, upper, var = v)
}
bind_rows(lapply(c("age", "karno", "wt_loss"), one)) |>
ggplot(aes(x, yhat)) +
geom_ribbon(aes(ymin = lower, ymax = upper), fill = pal[["blue"]], alpha = 0.18) +
geom_line(colour = pal[["blue"]], linewidth = 0.9) +
facet_wrap(~ var, scales = "free_x") +
labs(title = "Partial effects on the log relative hazard",
subtitle = "each predictor varied across its range, the others held at reference values",
x = NULL, y = "log relative hazard")

The bands are wide and every one of them comfortably includes a horizontal line. With 151 events and five predictors that is the honest picture.
Diagnostic 1: is the hazard really proportional?
The standard check uses scaled Schoenfeld residuals. At each event time, the Schoenfeld residual is the difference between the covariate value of the patient who died and the risk-set average. Under PH these residuals should have no trend in time; a trend means the coefficient is drifting.
z <- cox.zph(f)
z
## chisq df p
## rcs(age, 4) 0.636 3 0.888
## sex 2.330 1 0.127
## ecog 1.042 1 0.307
## karno 4.300 1 0.038
## rcs(wt_loss, 4) 0.555 3 0.907
## GLOBAL 7.370 9 0.599
sch <- bind_rows(lapply(colnames(z$y), function(v) {
tibble(time = z$time, resid = z$y[, v], term = v,
p = z$table[v, "p"])
})) |>
mutate(facet = sprintf("%s (p = %.3f)", term, p))
ggplot(sch, aes(time, resid)) +
geom_hline(yintercept = 0, colour = pal[["grey"]], linetype = "dashed") +
geom_point(alpha = 0.3, colour = pal[["blue"]], size = 1) +
geom_smooth(method = "loess", span = 0.9, colour = pal[["magenta"]],
fill = pal[["magenta"]], alpha = 0.15, linewidth = 0.9) +
facet_wrap(~ facet, scales = "free_y") +
labs(title = "Scaled Schoenfeld residuals",
subtitle = "a trend means the hazard ratio is changing with time",
x = "days", y = "scaled Schoenfeld residual")

The global test is reassuring (p = 0.60), but karno
alone comes in at p = 0.038 and its smoother visibly drifts upward.
Given the collinearity of the previous section, that coefficient was
already not interpretable; this says it is not even stable.
What a real violation looks like
To see an unmistakable one, fit the VA lung cancer trial – also in
survival, and famous for it.
v <- as_tibble(veteran) |>
transmute(time, dead = status == 1,
trt = factor(trt, 1:2, c("standard", "test")),
celltype, karno, age)
dv <- datadist(v)
assign("dv", dv, envir = globalenv())
options(datadist = "dv")
fv <- cph(Surv(time, dead) ~ karno + celltype + trt + age,
data = v, x = TRUE, y = TRUE, surv = TRUE)
zv <- cox.zph(fv)
zv
## chisq df p
## karno 12.977 1 0.00032
## celltype 14.884 3 0.00192
## trt 0.284 1 0.59381
## age 1.874 1 0.17098
## GLOBAL 29.179 6 5.6e-05
sv <- bind_rows(lapply(c("karno", "celltype"), function(vn) {
tibble(time = zv$time, resid = zv$y[, vn], term = vn, p = zv$table[vn, "p"])
})) |>
mutate(facet = sprintf("%s (p = %.5f)", term, p))
ggplot(sv, aes(time, resid)) +
geom_hline(yintercept = 0, colour = pal[["grey"]], linetype = "dashed") +
geom_point(alpha = 0.35, colour = pal[["orange"]], size = 1) +
geom_smooth(method = "loess", span = 0.8, colour = pal[["magenta"]],
fill = pal[["magenta"]], alpha = 0.15, linewidth = 0.9) +
facet_wrap(~ facet, scales = "free_y") +
labs(title = "A clear violation: the VA lung cancer trial",
subtitle = "the Karnofsky effect is strong early and gone later",
x = "days", y = "scaled Schoenfeld residual")

The Karnofsky smoother starts well below zero and climbs steadily to zero: performance status strongly predicts early death and says nothing about late death. One hazard ratio cannot describe that.
What to do about it
Three options, in rough order of how often they are the right answer.
Stratify. If the offending variable is a nuisance you do not need to estimate, give it its own baseline hazard. Each stratum gets its own \(h_{0s}(t)\), no proportionality is assumed between strata, and no coefficient is reported for it.
fv_s <- cph(Surv(time, dead) ~ karno + strat(celltype) + trt + age,
data = v, x = TRUE, y = TRUE)
cox.zph(fv_s)
## chisq df p
## karno 6.72046 1 0.0095
## trt 0.00466 1 0.9456
## age 2.52332 1 0.1122
## GLOBAL 12.18403 3 0.0068
Let the coefficient depend on time. If the change
is the finding, model it. survival::coxph does
this with tt():
fv_tt <- coxph(Surv(time, dead) ~ tt(karno) + celltype + trt + age,
data = v, tt = function(x, t, ...) x * log(t + 1))
round(summary(fv_tt)$coefficients[1:2, c("coef", "se(coef)", "Pr(>|z|)")], 4)
## coef se(coef) Pr(>|z|)
## tt(karno) -0.0065 0.0014 0.0000
## celltypesmallcell 0.8827 0.2722 0.0012
The interaction with \(\log t\) is significant and positive: the (negative) Karnofsky effect shrinks toward zero as time passes, exactly as the residual plot showed.
Restrict the time horizon. If PH holds over the first year and the clinical question is one-year survival, fit to one year and say so.
Stratifying celltype fixed its own violation but left
karno still drifting – a reminder that these are separate
problems needing separate remedies.
Diagnostic 2: functional form
Schoenfeld residuals check proportionality. Martingale residuals from a null model check whether a covariate enters on the right scale. Plot them against each candidate predictor: a smoother that bends tells you the variable needs a transformation or a spline.
cc <- d |> filter(!is.na(age), !is.na(ecog), !is.na(karno), !is.na(wt_loss))
cc$mres <- residuals(coxph(Surv(time, dead) ~ 1, data = cc), type = "martingale")
bind_rows(lapply(c("age", "karno", "wt_loss"), \(v)
tibble(x = cc[[v]], mres = cc$mres, var = v))) |>
ggplot(aes(x, mres)) +
geom_point(alpha = 0.3, colour = pal[["blue"]], size = 1) +
geom_smooth(method = "loess", span = 0.95, colour = pal[["magenta"]],
fill = pal[["magenta"]], alpha = 0.15, linewidth = 0.9) +
facet_wrap(~ var, scales = "free_x") +
labs(title = "Martingale residuals from a null model",
subtitle = "curvature here would argue for a transformation or a spline",
x = NULL, y = "martingale residual")

All three smoothers are close to straight, which agrees with the
anova verdict that the nonlinear terms bought nothing. Two
diagnostics pointing the same way is more convincing than either alone –
and note that this one is computed without reference to the
fitted model, so it is not just the same test twice.
Predicted survival curves
Because we fitted with surv = TRUE, the baseline
survival is stored and the model can produce absolute risk, not just
hazard ratios. This is what a clinician actually wants.
profiles <- data.frame(
age = c(60, 60, 75, 75),
sex = factor(c("female", "male", "female", "male"), levels = c("male", "female")),
ecog = c(0, 1, 1, 2),
karno = c(90, 80, 80, 60),
wt_loss = c(0, 5, 10, 20))
est <- survest(f, profiles, times = c(180, 365, 547))
round(est$surv, 3)
## [,1] [,2] [,3]
## [1,] 0.899 0.719 0.595
## [2,] 0.708 0.344 0.186
## [3,] 0.763 0.432 0.267
## [4,] 0.476 0.101 0.027
tt <- seq(5, 900, by = 5)
se <- survest(f, profiles, times = tt, conf.int = FALSE)
labs_p <- sprintf("%s, age %d, ECOG %d, Karnofsky %d",
as.character(profiles$sex), profiles$age,
profiles$ecog, profiles$karno)
curves <- bind_rows(lapply(seq_len(nrow(profiles)), \(i)
tibble(t = tt, s = se$surv[i, ], who = labs_p[i])))
ggplot(curves, aes(t, s, colour = who)) +
geom_line(linewidth = 1) +
geom_vline(xintercept = 365, linetype = "dotted", colour = pal[["grey"]]) +
scale_colour_manual(values = unname(pal[c("blue", "cyan", "orange", "magenta")])) +
scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
labs(title = "Model-based survival curves for four patient profiles",
subtitle = "all share one baseline hazard, scaled by exp(X beta); dotted line = 1 year",
x = "days", y = "survival probability", colour = NULL) +
theme(legend.position = "top", legend.direction = "vertical")

Every curve here is the same shape, stretched. That is the proportional hazards assumption made visible: the model cannot produce curves that cross, no matter what covariate values you feed it. If you believe two groups’ curves genuinely cross, you need a stratified or time-varying model, not a different set of covariates.
Validation and calibration
The indexes printed with the fit are computed on the data that
produced the fit, so they are optimistic. validate
quantifies by how much: it refits the whole modelling process on
bootstrap resamples and measures the drop when each refit is applied
back to the original data.
set.seed(5)
val <- validate(f, B = 300)
round(val[c("Dxy", "R2", "Slope", "D"), ], 4)
## index.orig training test optimism index.corrected Lower Upper n
## Dxy 0.2980 0.3305 0.2753 0.0553 0.2427 0.1441 0.3413 300
## R2 0.1597 0.2017 0.1244 0.0773 0.0824 -0.0248 0.1758 300
## Slope 1.0000 1.0000 0.7317 0.2683 0.7317 0.4161 1.0942 300
## D 0.0267 0.0349 0.0202 0.0146 0.0120 -0.0091 0.0306 300
dxy <- val["Dxy", c("index.orig", "index.corrected")]
c(C_apparent = dxy[["index.orig"]] / 2 + 0.5,
C_corrected = dxy[["index.corrected"]] / 2 + 0.5)
## C_apparent C_corrected
## 0.6490000 0.6213554
Two numbers matter. The corrected \(D_{xy}\) gives a c-index of about 0.62 – modest, and genuinely lower than the apparent value. The calibration slope of 0.73 is the shrinkage factor: predictions are roughly that much too extreme, and a future patient’s predicted log-hazard should be pulled toward the average by that factor.
set.seed(6)
cal <- calibrate(f, u = 365, B = 300, m = 50)
## Using Cox survival estimates at 365 Days
cd <- as.data.frame(unclass(cal)[, c("pred", "calibrated", "calibrated.corrected")])
cal_long <- bind_rows(
transmute(cd, pred, actual = calibrated, curve = "apparent"),
transmute(cd, pred, actual = calibrated.corrected, curve = "bias-corrected (bootstrap)"))
ggplot(cal_long, aes(pred, actual, colour = curve, linetype = curve)) +
geom_abline(slope = 1, intercept = 0, colour = pal[["grey"]], linetype = "dashed") +
geom_line(linewidth = 0.9) +
geom_rug(data = tibble(pred = attr(cal, "predicted")), inherit.aes = FALSE,
aes(x = pred), sides = "b", alpha = 0.2, colour = pal[["grey"]]) +
scale_colour_manual(values = unname(pal[c("blue", "magenta")])) +
scale_linetype_manual(values = c("solid", "longdash")) +
scale_x_continuous(labels = scales::percent) +
scale_y_continuous(labels = scales::percent) +
coord_equal() +
labs(title = "Calibration at one year",
subtitle = "dashed = perfect; the gap between the curves is the optimism",
x = "predicted 1-year survival", y = "observed 1-year survival",
colour = NULL, linetype = NULL) +
theme(legend.position = "top")

The bias-corrected curve sits above the diagonal at the low end: the model under-predicts survival for the patients it judges worst. The vertical gap between the two curves is overfitting made visible, and nothing in the fitted model could have revealed it – only resampling can.
Missing data, properly
The fit above silently dropped 15 patients with a missing
ecog, karno or wt_loss.
Complete-case analysis is unbiased only if data are missing completely
at random, which is rarely plausible: patients too unwell to have weight
recorded are not a random subset.
Harrell’s tool is aregImpute – multiple imputation using
additive regression with predictive mean matching, drawing several
completed datasets so that the uncertainty of imputation is carried into
the standard errors.
set.seed(9)
# I() forces a linear term. Without it aregImpute tries to spline ecog and
# karno, which have too few distinct values, and stops with an error.
mi <- aregImpute(~ time + dead + age + sex + I(ecog) + I(karno) +
wt_loss + meal_cal,
data = d, n.impute = 5, nk = 3, pr = FALSE)
f_mi <- fit.mult.impute(
Surv(time, dead) ~ rcs(age, 4) + sex + ecog + karno + rcs(wt_loss, 4),
cph, mi, data = d,
# In current Hmisc, extra arguments for the fitter go through fitargs;
# passing x = TRUE, y = TRUE directly raises "unused arguments".
fitargs = list(x = TRUE, y = TRUE, surv = TRUE),
pr = FALSE)
c(complete_case_n = f$stats[["Obs"]], complete_case_events = f$stats[["Events"]],
imputed_n = f_mi$stats[["Obs"]], imputed_events = f_mi$stats[["Events"]])
## complete_case_n complete_case_events imputed_n
## 213 151 228
## imputed_events
## 165
cbind(cc_coef = coef(f), mi_coef = coef(f_mi),
cc_se = sqrt(diag(vcov(f))), mi_se = sqrt(diag(vcov(f_mi)))) |>
round(4)
## cc_coef mi_coef cc_se mi_se
## age 0.0392 0.0487 0.0391 0.0379
## age' -0.0829 -0.0998 0.0772 0.0740
## age'' 0.4942 0.5385 0.3645 0.3513
## sex=female -0.6173 -0.5829 0.1796 0.1717
## ecog 0.7281 0.6842 0.1954 0.1834
## karno 0.0154 0.0114 0.0098 0.0093
## wt_loss -0.0216 -0.0198 0.0311 0.0316
## wt_loss' 0.1669 0.1232 0.2323 0.2199
## wt_loss'' -0.3590 -0.2784 0.4639 0.4639
All 228 patients and 165 events are back. The coefficients barely move, which is the common and reassuring case; the standard errors mostly shrink slightly, because 15 extra patients outweigh the imputation uncertainty.
The point is not that the answer changed. It is that you now know it did not – which is a result, and one a complete-case analysis cannot give you.
The nomogram
A nomogram converts the fitted model into something usable at a desk: each predictor contributes points, the points are totalled, and the total maps to a predicted survival probability.
# The one base-graphics figure here: rms draws nomograms itself, and there is
# no ggplot equivalent.
surv_fn <- Survival(f)
nom <- nomogram(f,
fun = list(\(x) surv_fn(365, x), \(x) surv_fn(730, x)),
funlabel = c("1-year survival", "2-year survival"),
fun.at = c(0.05, 0.1, 0.25, 0.5, 0.7, 0.85, 0.95))
plot(nom, xfrac = 0.45, cex.axis = 0.8)

A nomogram is only as good as the model behind it, and this one
carries all the caveats above – a corrected c-index near 0.62, a
shrinkage slope of 0.73, and two collinear performance-status scales. It
is included because it is the natural endpoint of the rms
workflow, not because this particular model deserves to be used.
What to remember
The model. Covariates multiply a baseline hazard that is never estimated. That buys enormous flexibility in the shape of survival over time, at the cost of one strong assumption about how covariates act.
Before fitting. Count events, not patients, and budget about 15 per parameter. Count distinct values to decide how flexibly each predictor can be fitted. Reduce collinear measurements to one summary. Do not let the outcome choose the model.
After fitting. anova for relative
strength, summary and Predict for
interpretable effects, cox.zph for proportionality,
martingale residuals for functional form, validate and
calibrate for what will happen on new data.
The habits that matter most are the unglamorous ones: not using a significance test to delete terms, not interpreting one coefficient of a collinear pair, not reporting an apparent c-index, and not treating complete-case analysis as the default.
References
- Harrell FE. Regression Modeling Strategies, 2nd ed. Springer, 2015. Chapters 17–21.
- Harrell FE. Biostatistics for Biomedical Research, hbiostat.org.
- Cox DR. Regression models and life-tables. J R Stat Soc B 1972;34:187–220.
- Therneau TM, Grambsch PM. Modeling Survival Data: Extending the Cox Model. Springer, 2000.
- Grambsch PM, Therneau TM. Proportional hazards tests and diagnostics based on weighted residuals. Biometrika 1994;81:515–526.
- Loprinzi CL, et al. Prospective evaluation of prognostic variables from patient-completed questionnaires. North Central Cancer Treatment Group. J Clin Oncol 1994;12:601–607.