set.seed(2026)
N <- 200L
x <- rbinom(N, size = 1, prob = 0.5)
beta0_true <- log(0.05) # log baseline hazard
beta1_true <- -0.7 # log hazard ratio for x = 1
event_time <- rexp(N, rate = exp(beta0_true + beta1_true * x))
cens_time <- rexp(N, rate = 0.03)
y <- pmin(event_time, cens_time)
event <- as.integer(event_time <= cens_time) # 1 = event, 0 = censored
surv_model <- "model {
C <- 10000
for (i in 1:N) {
log(lambda[i]) <- beta0 + beta1 * x[i]
# exponential log-likelihood, right-censored:
loglik[i] <- event[i] * log(lambda[i]) - lambda[i] * y[i]
phi[i] <- C - loglik[i]
zeros[i] ~ dpois(phi[i])
}
beta0 ~ dnorm(0, 0.01)
beta1 ~ dnorm(0, 0.01)
HR <- exp(beta1) # hazard ratio for x = 1 vs x = 0
}"
jags_surv <- run.jags(
model = surv_model,
data = list(y = y, x = x, event = event, N = N, zeros = rep(0, N)),
monitor = c("beta0", "beta1", "HR"),
n.chains = 2, inits = initsfunction,
burnin = 1000, sample = 4000, method = "rjags"
)
#> Compiling rjags model...
#> Calling the simulation using the rjags method...
#> Adapting the model for 1000 iterations...
#> Burning in the model for 1000 iterations...
#> Running the model for 4000 iterations...
#> Simulation complete
#> Calculating summary statistics...
#> Calculating the Gelman-Rubin statistic for 3 variables....
#> Finished running the simulation
summary(jags_surv)[, c("Mean", "Lower95", "Upper95", "psrf")] |> round(3)
#> Mean Lower95 Upper95 psrf
#> beta0 -3.115 -3.386 -2.861 1.000
#> beta1 -0.532 -0.933 -0.139 1.002
#> HR 0.600 0.374 0.843 1.002