# Cox proportional hazards and the PH assumption
# https://tidyecology.com/posts/cox-proportional-hazards/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-15

## ---- setup ----
library(survival)
library(ggplot2)
library(dplyr)

## ---- theme ----
te_ink <- "#16241d"; te_body <- "#2c3a31"; te_forest <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line <- "#dad9ca"; te_gold <- "#c9b458"; te_deep <- "#1d5b4e"
te_brick <- "#b5534e"; te_faint <- "#5d6b61"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = te_body),
          plot.title = element_text(colour = te_ink, face = "bold"),
          plot.subtitle = element_text(colour = te_faint),
          axis.title = element_text(colour = te_label),
          axis.text = element_text(colour = te_body),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          plot.background = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          legend.background = element_rect(fill = te_paper, colour = NA),
          legend.position = "none")
}

## ---- data ----
set.seed(414)
n <- 220
parasite <- round(rnorm(n), 3)                        # standardised parasite load
stage <- factor(sample(c("Juvenile", "Adult"), n, replace = TRUE))
shape <- ifelse(stage == "Juvenile", 0.85, 1.75)      # different shape => non-proportional
scale <- 26 * exp(-0.45 * parasite)                   # higher load => shorter life (proportional)
tt <- rweibull(n, shape = shape, scale = scale)
ct <- pmin(rexp(n, 1 / 70), 42)                       # loss to follow-up plus admin end
time <- pmin(tt, ct); status <- as.integer(tt <= ct)
d <- data.frame(time = round(time, 2), status = status, parasite = parasite, stage = stage)
c(n = n, events = sum(d$status), censored_fraction = round(mean(d$status == 0), 3))

## ---- fit ----
m <- coxph(Surv(time, status) ~ parasite + stage, data = d)
summary(m)$coefficients
round(exp(confint(m)), 3)

## ---- zph ----
z <- cox.zph(m)
z

## ---- fig-schoenfeld ----
sr <- data.frame(time = z$time, resid = z$y[, "stage"])
beta_stage <- coef(m)["stageJuvenile"]

ggplot(sr, aes(time, resid)) +
  geom_hline(yintercept = beta_stage, colour = te_faint, linetype = "42", linewidth = 0.5) +
  geom_point(colour = te_sage, size = 1.1, alpha = 0.8) +
  geom_smooth(method = "loess", formula = y ~ x, se = TRUE,
              colour = te_brick, fill = te_brick, alpha = 0.15, linewidth = 0.9) +
  annotate("text", x = 25, y = beta_stage + 0.15,
           label = "constant-effect reference", colour = te_faint, hjust = 0.5, size = 3.0) +
  labs(title = "The stage effect is not proportional",
       subtitle = "Scaled Schoenfeld residuals trend with time instead of staying flat",
       x = "Months since tagging", y = "Scaled Schoenfeld residual (stage)") +
  theme_te()

## ---- fig-cross ----
kfit <- survfit(Surv(time, status) ~ stage, data = d)
grid <- seq(0, 42, by = 0.25)
kd <- lapply(levels(d$stage), function(g) {
  s <- summary(kfit[paste0("stage=", g)])
  data.frame(stage = g, time = grid, surv = stepfun(s$time, c(1, s$surv))(grid))
}) |> bind_rows()

ggplot(kd, aes(time, surv, colour = stage)) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c(Adult = te_forest, Juvenile = te_gold)) +
  annotate("text", x = 40, y = 0.38, label = "Juvenile", colour = "#8a7a30", hjust = 1, size = 3.2) +
  annotate("text", x = 40, y = 0.11, label = "Adult", colour = te_forest, hjust = 1, size = 3.2) +
  coord_cartesian(ylim = c(0, 1)) +
  labs(title = "The stage survival curves cross",
       subtitle = "Juveniles die faster early, adults faster late",
       x = "Months since tagging", y = "Survival probability") +
  theme_te()

## ---- strata ----
m2 <- coxph(Surv(time, status) ~ parasite + strata(stage), data = d)
c(parasite_HR = round(exp(coef(m2)["parasite"]), 3),
  lower = round(exp(confint(m2)["parasite", 1]), 3),
  upper = round(exp(confint(m2)["parasite", 2]), 3))
cox.zph(m2)$table["GLOBAL", ]
