I am attempting to simulate survival data with a delayed treatment effect. The simsurv package has been very helpful: https://cran.r-project.org/web/packages/simsurv/vignettes/simsurv_usage.html
My approach is to define a piece-wise constant hazard function that has this form:
h(t) = λ1, for 0 ≤ t < T1
h(t) = λ2, for T1 ≤ t < T2
For some reason, the simulated survival curves have large 'steps' in the second interval. My guess is, that I can't use if-statements when defining the hazard function.
If anyone has suggestions how to fix this or knows a scource for explanations on how to define such a formula in R please let me know.
library(simsurv)
library(survival)
# user-defined hazard function with two intervals
piecewise_hazard <- function(t, x, betas) {
### calculate hazard at time t
ifelse(test = (t <= 5),
yes = betas[["beta1"]],
no = betas[["beta2"]] * x[["treatment"]])
}
### Set simulation parameters
set.seed(1234)
n <- 1000
t_max = 10
# Covariate data
covs <- data.frame(id = 1:n,
treatment = rep(c(1,2), each = (n/2)))
# Population (fixed effect) parameters
betas <- c(0.02, 0.1)
names(betas) <- c("beta1", "beta2")
### Simulation
sim_times <- simsurv(hazard = piecewise_hazard,
x = covs,
betas = betas,
maxt = t_max)
sim_data <- merge(sim_times, covs)
fit_km <- survfit(Surv(eventtime, status) ~ treatment, data = sim_data)
plot(fit_km, #clearly needs to match prior model output
conf.int = FALSE,
col = c("red", "blue"),
main = "Simulated delayed effect", xlab = "t", ylab = "S(t)")
# Censoring happens only at the end of follow-up at t_max
fit_km$n.censor[fit_km$n.censor > 0]```
