# Competing risks and cumulative incidence
# https://tidyecology.com/posts/competing-risks-cumulative-incidence/
#
# 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(ggplot2)
library(survival)
library(grid)

FOREST <- "#275139"; GOLD <- "#c9b458"; RUST <- "#b5534e"; SAGE <- "#93a87f"
INK <- "#16241d"; BODY <- "#2c3a31"; LINE <- "#dad9ca"

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.title = element_text(colour = INK, face = "bold", size = 12),
          plot.subtitle = element_text(colour = BODY, size = 10),
          axis.title = element_text(colour = BODY),
          axis.text = element_text(colour = BODY),
          legend.position = "none",
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = LINE, linewidth = 0.3),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA))
}

two_panel <- function(pa, pb) {
  grid.newpage()
  pushViewport(viewport(layout = grid.layout(1, 2)))
  print(pa, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
  print(pb, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
}

## ---- sim-a ----
set.seed(4256)
n <- 300; rate_pred <- 0.30; rate_other <- 0.45; tau <- 2.5
t_pred  <- rexp(n, rate_pred)
t_other <- rexp(n, rate_other)
obs_t <- pmin(t_pred, t_other, tau)
cause <- ifelse(obs_t == tau, 0L, ifelse(t_pred < t_other, 1L, 2L))

n_pred  <- sum(cause == 1)
n_other <- sum(cause == 2)
n_cens  <- sum(cause == 0)

## ---- cif-a ----
km_pred <- survfit(Surv(obs_t, cause == 1) ~ 1)
naive_cif <- 1 - summary(km_pred, times = tau, extend = TRUE)$surv

ev <- factor(cause, levels = c(0, 1, 2), labels = c("censor", "pred", "other"))
aj <- survfit(Surv(obs_t, ev) ~ 1)
pred_col  <- which(aj$states == "pred")
other_col <- which(aj$states == "other")
si <- summary(aj, times = tau, extend = TRUE)
aj_cif_pred  <- si$pstate[, pred_col]
aj_cif_other <- si$pstate[, other_col]

theo_cif <- (rate_pred / (rate_pred + rate_other)) *
  (1 - exp(-(rate_pred + rate_other) * tau))
overstate_pct <- 100 * (naive_cif - aj_cif_pred) / aj_cif_pred

## ---- coherence-a ----
cif_total  <- aj_cif_pred + aj_cif_other
km_all     <- survfit(Surv(obs_t, cause > 0) ~ 1)      # all-cause mortality, estimated
allcause   <- 1 - summary(km_all, times = tau, extend = TRUE)$surv
surv_total <- 1 - exp(-(rate_pred + rate_other) * tau) # population value from the true rates

## ---- fig-cif ----
naive_df <- data.frame(
  time = c(0, km_pred$time),
  cif  = c(0, 1 - km_pred$surv),
  what = "one minus Kaplan-Meier")
aj_df <- data.frame(
  time = c(0, aj$time),
  cif  = c(0, aj$pstate[, pred_col]),
  what = "cumulative incidence")
cif_lines <- rbind(naive_df, aj_df)

p1 <- ggplot(cif_lines, aes(time, cif, colour = what)) +
  geom_step(linewidth = 0.9) +
  scale_colour_manual(values = c("one minus Kaplan-Meier" = RUST,
                                 "cumulative incidence" = FOREST)) +
  annotate("text", x = 1.15, y = 0.55, label = "one minus KM", colour = RUST, hjust = 0, size = 3.4) +
  annotate("text", x = 1.35, y = 0.24, label = "cumulative incidence", colour = FOREST, hjust = 0, size = 3.4) +
  labs(title = "Predation risk, two estimators", x = "years", y = "probability of death by predation") +
  coord_cartesian(ylim = c(0, 0.7)) +
  theme_te()

stack_df <- data.frame(
  time = c(0, aj$time),
  lower = c(0, aj$pstate[, pred_col]),
  upper = c(0, aj$pstate[, pred_col] + aj$pstate[, other_col]))
p2 <- ggplot(stack_df, aes(time)) +
  geom_step(aes(y = upper), colour = GOLD, linewidth = 0.9) +
  geom_step(aes(y = lower), colour = FOREST, linewidth = 0.9) +
  annotate("text", x = 1.2, y = 0.18, label = "predation", colour = FOREST, hjust = 0, size = 3.4) +
  annotate("text", x = 1.5, y = 0.5, label = "other causes", colour = "#8a7420", hjust = 0, size = 3.4) +
  annotate("text", x = 1.7, y = 0.92, label = "still alive", colour = SAGE, hjust = 0, size = 3.4) +
  labs(title = "Stacked cumulative incidence", x = "years", y = "cumulative probability") +
  coord_cartesian(ylim = c(0, 1)) +
  theme_te()

two_panel(p1, p2)

## ---- sim-b ----
set.seed(42562)
nb <- 1200
x <- rbinom(nb, 1, 0.5)
h_pred  <- 0.25 * exp(log(1.8) * x)
h_other <- 0.40 * exp(log(1.8) * x)
taub <- 3
tp <- rexp(nb, h_pred); to <- rexp(nb, h_other)
tb <- pmin(tp, to, taub)
cb <- ifelse(tb == taub, 0L, ifelse(tp < to, 1L, 2L))
db <- data.frame(time = tb, cause = cb, x = x)

## ---- fit-b ----
csh <- coxph(Surv(time, cause == 1) ~ x, data = db)
csh_hr <- exp(coef(csh)); csh_ci <- exp(confint(csh))

evb <- factor(cb, levels = c(0, 1, 2), labels = c("censor", "pred", "other"))
fg <- finegray(Surv(time, evb) ~ ., data = data.frame(time = tb, x = x, evb = evb),
               etype = "pred")
fgm <- coxph(Surv(fgstart, fgstop, fgstatus) ~ x, weight = fgwt, data = fg)
fg_hr <- exp(coef(fgm)); fg_ci <- exp(confint(fgm))

cif_group <- function(sub) {
  e <- factor(sub$cause, levels = c(0, 1, 2), labels = c("c", "pred", "other"))
  a <- survfit(Surv(sub$time, e) ~ 1)
  s <- summary(a, times = taub, extend = TRUE)
  s$pstate[, which(a$states == "pred")]
}
cif_x0 <- cif_group(db[db$x == 0, ])
cif_x1 <- cif_group(db[db$x == 1, ])

## ---- fig-hazards ----
forest_df <- data.frame(
  model = factor(c("cause-specific\nhazard", "Fine-Gray\nsubdistribution"),
                 levels = c("Fine-Gray\nsubdistribution", "cause-specific\nhazard")),
  hr = c(csh_hr, fg_hr),
  lo = c(csh_ci[1], fg_ci[1]),
  hi = c(csh_ci[2], fg_ci[2]))
p3 <- ggplot(forest_df, aes(hr, model)) +
  geom_vline(xintercept = 1, colour = LINE, linewidth = 0.5) +
  geom_pointrange(aes(xmin = lo, xmax = hi), colour = FOREST, linewidth = 0.8, size = 0.6) +
  labs(title = "Two hazard ratios", x = "hazard ratio for predation", y = NULL) +
  coord_cartesian(xlim = c(0.8, 2.3)) +
  theme_te()

g0 <- db[db$x == 0, ]; g1 <- db[db$x == 1, ]
grid_cif <- function(sub, lab) {
  e <- factor(sub$cause, levels = c(0, 1, 2), labels = c("c", "pred", "other"))
  a <- survfit(Surv(sub$time, e) ~ 1)
  pc <- which(a$states == "pred")
  data.frame(time = c(0, a$time), cif = c(0, a$pstate[, pc]), grp = lab)
}
cif_x_df <- rbind(grid_cif(g0, "x = 0"), grid_cif(g1, "x = 1"))
p4 <- ggplot(cif_x_df, aes(time, cif, colour = grp)) +
  geom_step(linewidth = 0.9) +
  scale_colour_manual(values = c("x = 0" = SAGE, "x = 1" = FOREST)) +
  annotate("text", x = 2.0, y = 0.33, label = "x = 1", colour = FOREST, hjust = 0, size = 3.4) +
  annotate("text", x = 2.0, y = 0.20, label = "x = 0", colour = "#5d7a5f", hjust = 0, size = 3.4) +
  labs(title = "Predation incidence by habitat", x = "years", y = "cumulative incidence of predation") +
  coord_cartesian(ylim = c(0, 0.4)) +
  theme_te()

two_panel(p3, p4)

## ---- mc-c ----
set.seed(425699)
B <- 1000
truth <- (rate_pred / (rate_pred + rate_other)) *
  (1 - exp(-(rate_pred + rate_other) * tau))
naive_mc <- aj_mc <- numeric(B)
for (b in 1:B) {
  tp <- rexp(300, rate_pred); to <- rexp(300, rate_other)
  tm <- pmin(tp, to, tau)
  cc <- ifelse(tm == tau, 0L, ifelse(tp < to, 1L, 2L))
  naive_mc[b] <- 1 - summary(survfit(Surv(tm, cc == 1) ~ 1), times = tau, extend = TRUE)$surv
  e <- factor(cc, levels = c(0, 1, 2), labels = c("c", "p", "o"))
  aa <- survfit(Surv(tm, e) ~ 1)
  aj_mc[b] <- summary(aa, times = tau, extend = TRUE)$pstate[, which(aa$states == "p")]
}
naive_bias <- mean(naive_mc) - truth
aj_bias <- mean(aj_mc) - truth
