## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
has_rfsrc <- requireNamespace("randomForestSRC", quietly = TRUE)
has_ggplot2 <- requireNamespace("ggplot2", quietly = TRUE)

## ----setup, message=FALSE, warning=FALSE--------------------------------------
library(SuperSurv)
set.seed(123)

# Load built-in data
data("metabric", package = "SuperSurv")
metabric <- metabric[sample(seq_len(nrow(metabric)), 200), ]

# Define predictors and time grid
X <- metabric[, grep("^x", names(metabric))]
new.times <- seq(10, 150, by = 10)

## ----train-model--------------------------------------------------------------
event_library <- c("surv.coxph", "surv.weibull")
if (has_rfsrc) {
  rf_library <- create_grid("surv.rfsrc", list(ntree = 50))
  event_library <- c("surv.coxph", rf_library)
}

fit <- SuperSurv(
  time = metabric$duration,
  event = metabric$event,
  X = X,
  newdata = X,
  new.times = new.times,
  event.library = event_library,
  cens.library = c("surv.coxph"),
  nFolds = 3,
  verbose = FALSE,
  control = list(
    saveFitLibrary = TRUE,
    event.t.grid = seq(0, max(metabric$duration[metabric$event == 1]), length.out = 30),
    cens.t.grid = seq(0, max(metabric$duration[metabric$event == 0]), length.out = 30)
  )
)

## ----causal-effect------------------------------------------------------------
# Estimate the adjusted difference up to tau = 100 months
results <- estimate_marginal_rmst(
  fit = fit, 
  data = metabric, 
  trt_col = "x4", 
  times = new.times, 
  tau = 100
)



print(results$ATE_RMST)

## ----plot-curve, eval=has_ggplot2---------------------------------------------
# Plot the Delta RMST across a sequence of tau values
tau_grid <- seq(20, 140, by = 30)
plot_marginal_rmst_curve(
  fit = fit, 
  data = metabric, 
  trt_col = "x4", 
  times = new.times, 
  tau_seq = tau_grid
)

## ----plot-obs, eval=has_ggplot2-----------------------------------------------
plot_rmst_vs_obs(
  fit = fit, 
  data = metabric, 
  time_col = "duration", 
  event_col = "event", 
  times = new.times, 
  tau = 100
)

