Skip to contents

Patients treated at one institution are often more alike than patients from different institutions, and a survival model that ignores this can give the wrong standard errors, or hazard ratios that answer a different question from the one asked. This article works through one study:

  1. fit a Cox model and check it: proportional hazards and outliers (pm_check(), residplot());
  2. compare the performance scores: hazard ratios with simultaneous limits, a forest plot and survival curves (predictmeans(), autoplot(), survmeans());
  3. see how the hazard ratios change with the handling of ties, a baseline per sex and robust SEs by institution;
  4. model the institutions as random effects (frailty models and coxme()): conditional against population-averaged hazard ratios;
  5. fit accelerated failure time models, choose the distribution with a Cox-Snell plot, and read time ratios and median survival times;
  6. fit a Bayesian Weibull model with a random institution effect (brms): ratios per posterior draw, and the survival of a typical institution against that of all institutions.

The numbers that SAS can also give were checked against PROC PHREG and PROC LIFEREG (Checks).

The data are the lung cancer study of the North Central Cancer Treatment Group (Loprinzi et al. 1994), in the survival package: survival time in days of patients with advanced lung cancer at 18 institutions, with the ECOG performance score (0 fully active to 3 in bed most of the day), sex and age; status is 1 for a censored time and 2 for a death. The 226 patients with all these variables are used:

lung2 <- lung[complete.cases(lung[, c("time", "status", "ph.ecog", "sex", "age", "inst")]), ]
lung2$ecog <- factor(lung2$ph.ecog)
lung2$sex <- factor(lung2$sex, labels = c("male", "female"))
lung2$inst <- factor(lung2$inst)
table(ecog = lung2$ecog, status = lung2$status)
##     status
## ecog  1  2
##    0 26 37
##    1 31 82
##    2  6 43
##    3  0  1

One patient has ecog 3. The comparisons with that level are estimated, but with SEs five times the others, and the output flags them.

1. A Cox model and its checks

cox <- coxph(Surv(time, status) ~ ecog + sex + age, data = lung2)

A Cox model assumes that the hazard ratios do not change in time. pm_check() gives the test of Grambsch and Therneau (1994) for each term (cox.zph()) and counts the deviance residuals beyond 3; residplot() draws the deviance residuals against the linear predictor and the scaled Schoenfeld residuals against time, one panel per coefficient:

## Checks of a coxph model (226 observations)
## 
## Fit
##   OK Fit                                 no warnings                           
## 
## Residuals
##   !  Outliers (|deviance residual| > 3)  1 of 226: 57 (3.2)                    
## 
## Proportional hazards
##   OK Proportional hazards: ecog          3 df, km time                     0.11
##   OK Proportional hazards: sex           1 df, km time                     0.11
##   OK Proportional hazards: age           1 df, km time                     0.64
##   OK Proportional hazards: all terms     5 df, km time                     0.13
## 
## Notes
## ! Outliers (|deviance residual| > 3): Check these observations (times,
##     censoring, covariates) before anything else.
## 
## 1 worth a look: Outliers (|deviance residual| > 3).
## (! worth a look, i information, OK no concern.) Checks inform, they do not decide; see residplot().
plot of chunk unnamed-chunk-4

plot of chunk unnamed-chunk-4

No term departs from proportional hazards (p = 0.11, 0.11 and 0.64; 0.13 for all terms together), and the Schoenfeld residuals are flat in time. One patient (row 57) has a deviance residual of 3.2, a death much earlier than the model expects; it is worth a look, not a reason to drop it.

2. Hazard ratios and survival curves

A Cox model has no intercept, so its means are log hazards relative to the data’s average linear predictor, the same whatever the coding of the factors; their differences are the log hazard ratios. With adj = "tukey" the p-values and limits are simultaneous over the six pairs of scores:

pm_cox <- predictmeans(cox, "ecog", pairwise = TRUE, adj = "tukey")
pm_cox$pairs[, c("level1", "level2", "estimate", "std.error", "p.adj", "hazard.ratio", "adj.conf.low",
                 "adj.conf.high")]
##   level1 level2   estimate std.error        p.adj hazard.ratio adj.conf.low
## 1      0      1 -0.4090879 0.1995986 0.1699948346    0.6642559   -0.9218630
## 2      0      2 -0.9143787 0.2291802 0.0003847745    0.4007655   -1.5031498
## 3      1      2 -0.5052908 0.1909457 0.0405955000    0.6033301   -0.9958363
## 4      0      3 -1.9454057 1.0296870 0.2325679102    0.1429292   -4.5907042
## 5      1      3 -1.5363178 1.0209624 0.4345647311    0.2151719   -4.1592027
## 6      2      3 -1.0310270 1.0238243 0.7453042452    0.3566405   -3.6612642
##   adj.conf.high
## 1    0.10368723
## 2   -0.32560759
## 3   -0.01474537
## 4    0.69989283
## 5    1.08656705
## 6    1.59921028
advice(pm_cox)$text
## [1] "Mean(s) with SE over 3 times the median: 3. Few data or extrapolation (empty cells, covariate far from its data); check the counts (n) before comparing them."
## [2] "3 of 6 pairs are judged differently by the average LSD than by their own test (LSDs 0.491 to 2.65): use the p-values or pairs$lsd."

The rows are level1 against level2, so a hazard ratio below 1 is a lower hazard for the better score. Against ecog 0, a patient with ecog 1 has 1.51 times the hazard (1/0.664) and one with ecog 2 has 2.5 times (adjusted p = 0.0004); ecog 1 and 2 also differ (p = 0.04). The advice says what to make of ecog 3 and that the average LSD misleads here: read each pair’s own test.

The forest plot of the hazard ratios, on a log axis with the simultaneous limits (filled points: significant after the adjustment):

autoplot(pm_cox, type = "pairs")
plot of chunk unnamed-chunk-6

plot of chunk unnamed-chunk-6

survmeans() gives the survival curve of each score for one covariate pattern, here women of average age, from survfit() of the fitted model, with pointwise limits and the median survival time. (A curve averaged over the sexes would have no exact limits, so the pattern is stated rather than averaged over.)

sm_cox <- survmeans(cox, "ecog", at = list(sex = "female"))
sm_cox$medians
##   ecog median conf.low conf.high
## 1    0    567      433       814
## 2    1    426      340       567
## 3    2    286      212       394
## 4    3    147       60        NA
autoplot(sm_cox)
plot of chunk unnamed-chunk-7

plot of chunk unnamed-chunk-7

The median survival falls from 567 days for ecog 0 to 426 and 286 days for ecog 1 and 2.

3. Ties, strata and robust SEs

The same hazard ratios under three variations of the model: Breslow’s approximation for tied times (Efron’s is coxph’s default and SAS’s choice here), a baseline hazard of its own for each sex (strata(sex)), and robust (sandwich) SEs by institution, which allow for patients of one institution being alike without modelling it:

hr <- function(fit) {
  p <- predictmeans(fit, "ecog", pairwise = TRUE)$pairs
  p <- p[p$level1 != "3" & p$level2 != "3", ]
  setNames(round(p$hazard.ratio, 3), paste(p$level1, p$level2, sep = "/"))
}
rob <- coxph(Surv(time, status) ~ ecog + sex + age, data = lung2, cluster = inst)
rbind(Efron = hr(cox),
      Breslow = hr(coxph(Surv(time, status) ~ ecog + sex + age, data = lung2, ties = "breslow")),
      `strata(sex)` = hr(coxph(Surv(time, status) ~ ecog + age + strata(sex), data = lung2)),
      `robust by inst` = hr(rob))
##                  0/1   0/2   1/2
## Efron          0.664 0.401 0.603
## Breslow        0.664 0.401 0.604
## strata(sex)    0.696 0.401 0.577
## robust by inst 0.664 0.401 0.603
predictmeans(rob, "ecog", pairwise = TRUE)$pairs[1:3, c("level1", "level2", "estimate", "std.error")]
##   level1 level2   estimate std.error
## 1      0      1 -0.4090879 0.1048509
## 2      0      2 -0.9143787 0.2345056
## 3      1      2 -0.5052908 0.2109276
advice(predictmeans(rob, "ecog"))$text
## [1] "SEs are robust (sandwich) by inst: hazard ratios are population-averaged; the model-based SEs would ignore the clustering."

The ties hardly matter (there are few), and stratifying by sex moves the 0/1 ratio from 0.664 to 0.696. The robust SEs leave the hazard ratios as they are and change their SEs: smaller for ecog 0 against 1 (0.105 against 0.200), larger for 1 against 2. The advice line says that they are population-averaged.

4. Institutions as random effects

A shared frailty puts the institutions in the model: each has a random effect on the log hazard, gamma (frailty()), log-normal (frailty.gaussian()) or normal on the log hazard in coxme() (Therneau and Grambsch 2000). The hazard ratios are then conditional on the institution, those of a typical institution, and predictmeans says so:

library(coxme)
fr_gamma <- coxph(Surv(time, status) ~ ecog + sex + age + frailty(inst), data = lung2)
fr_lnorm <- coxph(Surv(time, status) ~ ecog + sex + age + frailty.gaussian(inst), data = lung2)
fr_coxme <- coxme(Surv(time, status) ~ ecog + sex + age + (1 | inst), data = lung2)
pm_fr <- predictmeans(fr_coxme, "ecog", pairwise = TRUE)
pm_fr$settings$back_transform$estimate
## [1] "hazard relative to the data's average linear predictor, for a typical inst"
advice(pm_fr)$text[grepl("conditional", advice(pm_fr)$text)]
## [1] "Hazard ratios are conditional on the inst effect (a typical cluster), not population-averaged; coxph(..., cluster = inst) gives population-averaged ones."
rbind(`no frailty` = hr(cox), `gamma frailty` = hr(fr_gamma), `log-normal frailty` = hr(fr_lnorm),
      coxme = hr(fr_coxme))
##                      0/1   0/2   1/2
## no frailty         0.664 0.401 0.603
## gamma frailty      0.661 0.389 0.589
## log-normal frailty 0.658 0.379 0.576
## coxme              0.658 0.380 0.578

The institution variance is small (gamma 0.012, log-normal 0.024, coxme 0.022), so the conditional hazard ratios are only a little further from 1 than those of the model without it. With a larger variance they move further away, while the population-averaged ratios of section 3 do not: a conditional ratio compares two patients of the same institution, a population-averaged one two patients drawn from all of them. The checks work for frailty fits too; the proportional-hazards test is then by term:

pm_check(fr_gamma)[, c("check", "result", "p.value")]
##                                check             result   p.value
## 1                                Fit        no warnings        NA
## 2 Outliers (|deviance residual| > 3) 1 of 226: 57 (3.2)        NA
## 3         Proportional hazards: ecog      3 df, km time 0.1124209
## 4          Proportional hazards: sex      1 df, km time 0.1089430
## 5          Proportional hazards: age   0.99 df, km time 0.6255444
## 6    Proportional hazards: all terms    6.3 df, km time 0.2520915

5. Accelerated failure time models

survreg() models log time, so a positive difference is a longer survival and its exponential a time ratio. Back-transformed, a mean is the median survival time (log-normal), the mean time (exponential) or the time by which 63% have died (Weibull), and the output names it. Which distribution? The Cox-Snell plot of residplot() (Cox and Snell 1968): the cumulative hazard of the residuals follows the 45-degree line when the distribution fits.

wb <- survreg(Surv(time, status) ~ ecog + sex + age, data = lung2, dist = "weibull")
aft <- survreg(Surv(time, status) ~ ecog + sex + age, data = lung2, dist = "lognormal")
residplot(wb)
plot of chunk unnamed-chunk-11

plot of chunk unnamed-chunk-11

plot of chunk unnamed-chunk-11

plot of chunk unnamed-chunk-11

The Weibull curve stays on the line up to its last few steps, where few deaths remain; the log-normal one lies below the line for small residuals and above it beyond about 1.3. The Weibull distribution fits better. The log-normal model is shown as well, for its medians:

pm_aft <- predictmeans(aft, "ecog", pairwise = TRUE)
pm_aft$means[, c("ecog", "estimate", "std.error", "response", "response.conf.low", "response.conf.high")]
##   ecog estimate std.error response response.conf.low response.conf.high
## 1    0 6.000726 0.1474788 403.7218         302.37646           539.0343
## 2    1 5.808808 0.1059430 333.2218         270.74139           410.1213
## 3    2 5.254338 0.1531425 191.3947         141.76687           258.3955
## 4    3 5.174084 1.0290101 176.6347          23.50613          1327.3057
pm_aft$settings$back_transform$estimate
## [1] "median survival time"
pm_aft$pairs[1:3, c("level1", "level2", "time.ratio", "time.ratio.conf.low", "time.ratio.conf.high", "p.value")]
##   level1 level2 time.ratio time.ratio.conf.low time.ratio.conf.high     p.value
## 1      0      1   1.211571           0.8570101             1.712819 0.277283361
## 2      0      2   2.109368           1.3959996             3.187273 0.000394067
## 3      1      2   1.741019           1.2107255             2.503580 0.002774168

Patients with ecog 0 live 2.1 times as long as those with ecog 2 (median 404 against 191 days, averaged over the sexes on the log-time scale, at the average age). For a Weibull model the hazard ratio of a difference d of log times is exp(-d / scale), so its hazard ratios can be set beside the Cox model’s:

pw <- predictmeans(wb, "ecog", pairwise = TRUE)$pairs
pw <- pw[pw$level1 != "3" & pw$level2 != "3", ]
rbind(`Weibull, exp(-d / scale)` = round(exp(-pw$estimate / wb$scale), 3), Cox = hr(cox))
##                            0/1   0/2   1/2
## Weibull, exp(-d / scale) 0.672 0.400 0.594
## Cox                      0.664 0.401 0.603

The two agree to about 0.01. The survival curves of the log-normal model, with delta-method limits:

autoplot(survmeans(aft, "ecog", at = list(sex = "female")))
plot of chunk unnamed-chunk-14

plot of chunk unnamed-chunk-14

6. A Bayesian Weibull model with a random institution effect

With 18 institutions and a variance near zero, the frequentist frailty variance is poorly determined. A Bayesian model carries the uncertainty of that variance, and of the Weibull shape, into every result. brms (Bürkner 2017) codes right censoring the other way round from Surv() (1 = censored), and compiles the model before sampling:

library(brms)
# cmdstanr compiles where rstan's toolchain does not (e.g. Windows); brms uses rstan otherwise
if (requireNamespace("cmdstanr", quietly = TRUE)) options(brms.backend = "cmdstanr")
lung2$censored <- as.integer(lung2$status == 1)
bw <- brm(time | cens(censored) ~ ecog + sex + age + (1 | inst), data = lung2, family = weibull(),
          chains = 2, iter = 2000, refresh = 0, seed = 1)

The same calls give posterior medians, equal-tailed credible intervals and the probability of direction (pd); the time ratios and the hazard ratios exp(-k d) are computed for each draw, with that draw’s shape k:

pm_check(bw)[, c("check", "result")]
##                   check
## 1    Convergence (Rhat)
## 2 Effective sample size
## 3 Divergent transitions
## 4          Model checks
##                                                        result
## 1                         largest 1.003 (sexfemale), 2 chains
## 2                 smallest bulk 1901, tail 1039 of 2000 draws
## 3                                                   0 of 2000
## 4 posterior predictive checks: pp_check() of brms or rstanarm
pb <- predictmeans(bw, "ecog", pairwise = TRUE)
pb$pairs[1:3, c("level1", "level2", "time.ratio", "hazard.ratio", "hazard.ratio.conf.low",
                "hazard.ratio.conf.high", "pd")]
##   level1 level2 time.ratio hazard.ratio hazard.ratio.conf.low
## 1      0      1   1.350609    0.6682899             0.4421597
## 2      0      2   2.063149    0.3788215             0.2340553
## 3      1      2   1.513507    0.5726082             0.3902866
##   hazard.ratio.conf.high     pd
## 1              0.9933809 0.9775
## 2              0.6225996 1.0000
## 3              0.8411816 0.9985
##                        vcov posterior.sd        2.5 %   97.5 %
## inst.(Intercept) 0.01505504   0.03167563 8.511708e-05 0.114769

The chains have converged (largest Rhat 1.003). The hazard ratios are close to the frequentist ones (0.68, 0.38, 0.57), with the institution variance estimated at 0.015 but anywhere from about 0 to 0.11. The survival of a typical institution and the survival of all institutions (marginal = TRUE, S(t) averaged over the institution effect for each draw) differ by only a few days here, as the institutions differ little:

sb <- survmeans(bw, "ecog", at = list(sex = "female"))
sbm <- survmeans(bw, "ecog", at = list(sex = "female"), marginal = TRUE)
cbind(sb$medians[, c("ecog", "median")], marginal = sbm$medians$median)
##   ecog   median marginal
## 1    0 565.6109 562.3549
## 2    1 418.5344 416.6677
## 3    2 275.7496 274.4512
## 4    3 176.7338 176.1324
plot of chunk unnamed-chunk-17

plot of chunk unnamed-chunk-17

The article on Bayesian fits covers the rest: convergence checks, R², joint regions and limits.

Checked against SAS

The SAS program dev/sas/survival.sas fits the models of sections 1-5 to the same 226 patients with PROC PHREG and PROC LIFEREG (SAS OnDemand, 30 November 2026; output dev/sas/survival-results-2026-11-30.pdf). predictmeans gives the same log hazard ratios, log time ratios and SEs:

SAS run hazard ratio 1 vs 0 (SE of log) largest difference over the six pairs: estimate, SE
PHREG, Efron ties 1.505 (0.1996) 2e-5, 5e-5
PHREG, Breslow ties 1.505 (0.1996) 5e-5, 4e-5
PHREG, strata sex 1.438 (0.2011) 4e-5, 4e-5
PHREG, covs(aggregate) by institution 1.505 (0.1049) 2e-5, 5e-5
PHREG, random inst / dist = gamma 1.514 (0.2009) 1e-5, 2e-5
PHREG, random inst / dist = lognormal 1.520 (0.2022) 5e-5, 2e-4
LIFEREG, Weibull, log-normal, exponential: four means and six pairs each 5e-5, 5e-5

The SAS values are printed to four decimals, so a difference below 5e-5 is agreement to every printed digit. The table leaves out the three pairs with ecog 3 (one patient): there the likelihood is flat, SAS stops at its convergence criterion (GCONV = 1e-8) before coxph does, and they differ by up to 3e-4. The frailty variances are estimated differently (SAS 0.0123 gamma, 0.0264 log-normal; coxph 0.0116 and 0.0243), so the frailty rows compare coxph fitted at SAS’s variances (frailty(inst, theta = 0.01229)); the log-normal SEs then agree within 0.1%, the rounding of the printed variance. The tests are in tests/testthat/test-survival.R.

The survival curves and medians of survmeans() equal survfit() (Cox) and predict() / psurvreg() (AFT) to 1e-10. The brms results are summaries of the draws, checked in tests/testthat/test-bayes.R: the hazard ratio of each draw and the closed-form S(t) by hand, the marginal curves against integrate(), and a flat-prior Weibull fit against survreg().

What is not supported

  • A Cox mean is relative to the data’s average linear predictor; only the differences between means, the log hazard ratios, answer a question. Terms that give no mean (tt(), pspline(), ridge(), an interaction with strata(), frailty(sparse = FALSE)) stop with a message that names their coefficients.
  • The tests are Wald z tests, as SAS’s. With very few events in a level (ecog 3: one patient) they are unreliable, and the advice says so; a likelihood-ratio test of the model is then better.
  • A frailty model’s hazard ratios use the fitted frailty variance as if it were known; with few clusters that understates their uncertainty. The Bayesian model of section 6 carries it.
  • Population-averaged hazard ratios come only from robust SEs (cluster =); survival curves averaged over the random effects only from brms fits (survmeans(marginal = TRUE), random intercepts).
  • survmeans() gives curves at one stated covariate pattern, with pointwise limits (not a band for the whole curve). Cox curves stop at the last follow-up time; coxme() fits and stratified survreg() fits have none.
  • brms cox() models give hazard ratios and survival curves from their spline baseline hazard, up to the spline’s upper boundary; a Weibull shape or log-normal sigma modelled by predictors gives no curves. The proportional-hazards checks are for coxph() fits; brms fits are checked with pp_check().
  • The SAS comparison covers the frequentist models. The brms results are checked against their closed forms per draw, integrate(), and survreg() within 5% with flat priors, and against SAS’s own Bayesian fits (dev/sas/survival-bayes.sas: LIFEREG and PHREG with a BAYES statement, and a PROC MCMC Weibull model with a random institution effect): time ratios within 0.5%, hazard ratios within 1.1%, survival probabilities and medians of the frailty model within 4.5%.

References

  • Bürkner, P.-C. (2017). brms: An R package for Bayesian multilevel models using Stan. Journal of Statistical Software, 80(1), 1-28.
  • Cox, D. R. and Snell, E. J. (1968). A general definition of residuals. Journal of the Royal Statistical Society, Series B, 30, 248-275.
  • Grambsch, P. M. and Therneau, T. M. (1994). Proportional hazards tests and diagnostics based on weighted residuals. Biometrika, 81, 515-526.
  • Loprinzi, C. L., Laurie, J. A., Wieand, H. S., et al. (1994). Prospective evaluation of prognostic variables from patient-completed questionnaires. Journal of Clinical Oncology, 12, 601-607.
  • Therneau, T. M. and Grambsch, P. M. (2000). Modeling Survival Data: Extending the Cox Model. Springer, New York.