Show code
reps <- 1000L # Replications per method. Full scale: 1000L.
iterations <- 10000L # Maximum iterations per subgroup variable. Full scale: 10000L.
tolerance <- 2e-3 # Stop when the loss falls below this value. Full scale: 2e-3.
simulated_datasets <- 50L # Simulated datasets. Full scale: 50L.
simulated_patients <- 600L # Patients per simulated dataset. Full scale: 600L.
simulated_reps <- 20L # Replications per simulated dataset and method. Full scale: 20L.Rendered on 2026-11-30 with retrogroup 0.0.3 at commit
35499a3.
Purpose
vignette("estimates", package = "retrogroup") estimates
a prognostic effect for each subgroup level from the assumed event
counts, and vignette("sampling", package = "retrogroup")
samples subgroups from the model in
vignette("model", package = "retrogroup"), which includes
these effects. So the prognostic hazard ratios of sampled datasets
should move away from 1 toward those of the true subgroups. The loss
function in
vignette("optimization", package = "retrogroup") targets
hazard ratios only, so we make no prediction about optimized datasets.
This vignette checks by simulation how well sampled and optimized
datasets recover the prognostic hazard ratios of the true subgroups.
Method
Model
For each subgroup variable, we fit the Cox model
survival::coxph(Surv(time, event) ~ treatment * level, ties = "efron")where level is the subgroup variable, and its reference
level is the first level in the summary statistics. The prognostic
hazard ratio of a non-reference level is the exponential of its main
effect coefficient: the hazard of that level relative to the reference
level in the control arm.
Design
Each example is a real or simulated randomized trial whose true subgroups are known. We fit the model to the true subgroups once to get the true prognostic hazard ratios. Each replication of each method then does the following:
- Hide the subgroups. Keep only the patient-level survival data and the summary statistics.
- Sampling. Draw a sampled dataset with the method’s sampler.
- Optimization. Optimize the sampled dataset toward the summary statistics with the method’s optimizer, and record the elapsed time and whether the optimizer warned.
- Comparison. Fit the model to the sampled dataset and to the optimized dataset, and subtract the true prognostic hazard ratios.
We run three examples:
-
Colon cancer example. The patients of
group_example_patient()and the summary statistics ofgroup_example_summary(), with true subgroups fromsurvival::colon. -
Primary biliary cholangitis example. The 312
randomized participants in the Mayo Clinic trial of D-penicillamine
versus placebo (
survival::pbc), with death as the event and transplant as censoring. The subgroups are hepatomegaly, spiders, edema, and histologic stage 4, each with levels “no” and “yes”, and the summary statistics come fromgroup_analysis_summary()on the true subgroups. This example is a stress test. All four subgroups are markers of advanced liver disease, and their prognostic hazard ratios are more extreme than those of most subgroups in published forest plots. -
Simulated example. Datasets of 600 patients each,
with 1:1 randomization and one subgroup variable of three levels. The
levels have prevalences \((0.3, 0.3,
0.4)\), prognostic hazard ratios \((1,
1.5, 2)\) relative to the first level, and treatment hazard
ratios \((0.5, 0.7, 0.9)\). Event times
are exponential with rate 0.1 in the control arm of the first level, and
censoring times are uniform on \((0,
20)\). The prognostic and treatment effects are both non-trivial
but moderate, and the data-generating model agrees with the model in
vignette("model", package = "retrogroup").
We test two methods:
-
Unconstrained.
group_sample_unconstrained()andgroup_optimize_unconstrained(). -
Constrained.
group_sample_constrained()andgroup_optimize_constrained().
Every optimization uses tolerance = 0.002 and at most 10000 iterations per subgroup variable.
Reporting
For each real-data example, a table shows the true prognostic hazard ratios with 95% Wald confidence intervals. For every example, a figure shows histograms of the prognostic hazard ratio of each sampled or optimized dataset minus the true one, with one panel per subgroup level, method, and stage (sampled or optimized). A histogram centered on zero means the reconstructed subgroups recover the true prognostic hazard ratio on average, and its width shows how much a single reconstructed dataset varies around the truth. A table shows the fraction of optimization runs that warned, and another figure shows histograms of the elapsed time of each optimization run.
Show code
# Shared code for the simulation vignettes:
# benchmarks_sampling, benchmarks_optimization, and prognostic.
#
# Each *.Rmd.source file loads this file into a folded chunk, so the code is
# baked into every rendered vignette. The roxygen2-style comments document
# the functions for reviewers. roxygen2 does not process this file.
#
# To try the examples, start R in the package root and run:
#
# library(retrogroup)
# library(ggplot2)
# source("vignettes/benchmarks.R")
#
# Every example runs in a few seconds.
#
# Results format
# --------------
#
# A benchmark is a list with two data frames:
#
# - estimates: one row per method, replication, subgroup level, and stage
# (if the vignette has stages). Columns:
# - method: factor, the reconstruction method.
# - replication: integer, the index of the replication within the method.
# - stage: factor, optional, e.g. "Sampled" or "Optimized".
# - subgroup: factor, "variable: level" or a similar label.
# - target: the value the reconstructed dataset should reproduce.
# - estimate: the value the reconstructed dataset achieves,
# NA if it cannot be computed.
# - difference: estimate minus target.
# - runs: one row per optimization run, or NULL if nothing is optimized.
# Columns: method, replication, seconds (elapsed time of the optimizer),
# and warned (TRUE if the loss did not fall below the tolerance).
# Simulation elements ---------------------------------------------------------
#' @title Colon cancer example data
#' @description Standardize the colon cancer example patients and summary
#' statistics of `group_example_patient()` and `group_example_summary()`.
#' @return A list with `patient` (output of `group_data_patient()`) and
#' `summary` (output of `group_data_summary()`).
#' @examples
#' colon <- example_colon()
#' colon$summary
example_colon <- function() {
list(
patient = group_data_patient(
group_example_patient(),
arm = "arm",
treatment = "Lev+5FU",
time = "time",
event = "event"
),
summary = group_data_summary(
group_example_summary(),
variable = "variable",
level = "level",
patients = "patients",
events = "events",
hazard_ratio = "hazard_ratio"
)
)
}
#' @title Reconstruction methods under test
#' @description Each method pairs a sampler with its matching optimizer.
#' @return A named list of methods. Each method is a list with:
#' - `sample`: the sampler, e.g. `group_sample_unconstrained()`.
#' - `optimize`: the optimizer, e.g. `group_optimize_unconstrained()`.
#' - `constrained`: `TRUE` if every sampled and optimized dataset must
#' reproduce the assumed counts of patients exactly.
#' @examples
#' methods <- benchmark_methods()
#' names(methods)
#' colon <- example_colon()
#' sampled <- methods$Constrained$sample(colon$patient, colon$summary)
#' table(sampled$age)
benchmark_methods <- function() {
list(
Unconstrained = list(
sample = group_sample_unconstrained,
optimize = group_optimize_unconstrained,
constrained = FALSE
),
Constrained = list(
sample = group_sample_constrained,
optimize = group_optimize_constrained,
constrained = TRUE
)
)
}
#' @title Subgroup labels
#' @description Label each row of a summary statistics data frame.
#' @param summary Data frame with `variable` and `level` columns, such as
#' the output of `group_data_summary()` or `group_analysis_summary()`.
#' @return Character vector with one `"variable: level"` label per row.
#' @examples
#' subgroup_label(example_colon()$summary)
subgroup_label <- function(summary) {
paste0(summary$variable, ": ", summary$level)
}
#' @title Check the counts of patients
#' @description Stop with an error unless the number of patients in each
#' subgroup level of a dataset equals the assumed count in `summary`.
#' Constrained methods promise exact counts, and the benchmarks call this
#' function to verify the promise on every dataset.
#' @param statistics Output of `group_analysis_summary()` for the dataset.
#' Levels with no patients may be missing.
#' @param summary Summary statistics with the assumed counts.
#' @param name Description of the dataset for the error message.
#' @return `NULL` (invisibly) if the counts match.
#' @examples
#' colon <- example_colon()
#' variables <- unique(colon$summary$variable)
#' sampled <- group_sample_constrained(colon$patient, colon$summary)
#' statistics <- group_analysis_summary(sampled, variables)
#' check_counts(statistics, colon$summary, "sampled dataset")
check_counts <- function(statistics, summary, name) {
rows <- match(subgroup_label(summary), subgroup_label(statistics))
observed <- statistics$patients[rows]
if (!identical(observed, summary$patients)) {
stop(
"The constrained ", name, " does not match the assumed counts.\n",
"Assumed patients: ", toString(summary$patients), "\n",
"Observed patients: ", toString(observed),
call. = FALSE
)
}
invisible()
}
#' @title Compare achieved hazard ratios with their targets
#' @description Pair each target hazard ratio with the hazard ratio a
#' reconstructed dataset achieves in the same subgroup level.
#' @param targets Summary statistics with the target hazard ratios.
#' @param achieved Output of `group_analysis_summary()` for the
#' reconstructed dataset. Levels with no patients may be missing,
#' and their estimates are `NA`.
#' @return Data frame with one row per row of `targets` and columns
#' `subgroup`, `target`, and `estimate`.
#' @examples
#' colon <- example_colon()
#' variables <- unique(colon$summary$variable)
#' sampled <- group_sample_unconstrained(colon$patient, colon$summary)
#' compare_summary(colon$summary, group_analysis_summary(sampled, variables))
compare_summary <- function(targets, achieved) {
rows <- match(subgroup_label(targets), subgroup_label(achieved))
data.frame(
subgroup = subgroup_label(targets),
target = targets$hazard_ratio,
estimate = achieved$hazard_ratio[rows]
)
}
#' @title Run one optimization
#' @description Call an optimizer and record its elapsed time and whether
#' it warned that the loss did not fall below the tolerance.
#' The warning is recorded, not shown.
#' @param optimize Optimizer, e.g. `group_optimize_constrained()`.
#' @param start Starting dataset, usually from the matching sampler.
#' @param summary Summary statistics with the target hazard ratios.
#' @param iterations Maximum number of iterations per subgroup variable.
#' @param tolerance Stop when the loss falls below this value.
#' @return List with `optimized` (the optimized dataset), `seconds`
#' (elapsed time of the optimizer only), and `warned` (logical).
#' @examples
#' colon <- example_colon()
#' start <- group_sample_constrained(colon$patient, colon$summary)
#' run <- optimize_once(
#' group_optimize_constrained,
#' start,
#' colon$summary,
#' iterations = 20L,
#' tolerance = 1e-3
#' )
#' run[c("seconds", "warned")]
optimize_once <- function(optimize, start, summary, iterations, tolerance) {
warned <- FALSE
seconds <- system.time(
optimized <- withCallingHandlers(
optimize(start, summary, iterations = iterations, tolerance = tolerance),
retrogroup_warning = function(condition) {
warned <<- TRUE
invokeRestart("muffleWarning")
}
)
)[["elapsed"]]
list(optimized = optimized, seconds = seconds, warned = warned)
}
#' @title Run a benchmark
#' @description Run independent replications of every method and
#' assemble the results in the format described at the top of this file.
#' @param methods Named list of methods, e.g. from `benchmark_methods()`.
#' @param reps Number of replications per method.
#' @param replication Function of one method that runs one replication.
#' It returns a list with:
#' - `estimates`: data frame with columns `subgroup`, `target`,
#' `estimate`, and optionally `stage`.
#' - `runs`: data frame with columns `seconds` and `warned`,
#' or `NULL` if the replication does not optimize.
#' @return List with `estimates` and `runs`. Factor levels of `method`,
#' `stage`, and `subgroup` follow their order of first appearance,
#' which fixes the order of panels in figures.
#' @examples
#' colon <- example_colon()
#' variables <- unique(colon$summary$variable)
#' replication <- function(method) {
#' sampled <- method$sample(colon$patient, colon$summary)
#' achieved <- group_analysis_summary(sampled, variables)
#' list(estimates = compare_summary(colon$summary, achieved), runs = NULL)
#' }
#' results <- run_benchmark(benchmark_methods(), reps = 2L, replication)
#' head(results$estimates)
run_benchmark <- function(methods, reps, replication) {
results <- lapply(names(methods), \(name) {
lapply(seq_len(reps), \(index) {
result <- replication(methods[[name]])
label <- function(data) {
if (is.null(data)) {
return(NULL)
}
cbind(method = name, replication = index, data)
}
list(estimates = label(result$estimates), runs = label(result$runs))
})
})
results <- unlist(results, recursive = FALSE)
estimates <- do.call(rbind, lapply(results, `[[`, "estimates"))
runs <- do.call(rbind, lapply(results, `[[`, "runs"))
estimates$difference <- estimates$estimate - estimates$target
for (column in intersect(c("method", "stage", "subgroup"), names(estimates))) {
estimates[[column]] <- in_order(estimates[[column]])
}
if (!is.null(runs)) {
runs$method <- in_order(runs$method)
}
list(estimates = estimates, runs = runs)
}
#' @title Factor in order of first appearance
#' @param x Vector.
#' @return Factor whose levels are the unique values of `x` in order.
#' @examples
#' in_order(c("b", "a", "b"))
in_order <- function(x) {
factor(x, levels = unique(x))
}
# Display ---------------------------------------------------------------------
#' @title Format numbers for tables
#' @description Show 3 decimal places, but switch to scientific notation
#' with 3 significant figures for nonzero values that would otherwise
#' round to zero.
#' @param x Numeric vector.
#' @return Character vector.
#' @examples
#' format_number(c(0.12345, 0.0001234, 0))
format_number <- function(x) {
ifelse(
x != 0 & round(x, 3L) == 0,
formatC(x, digits = 2L, format = "e"),
formatC(x, digits = 3L, format = "f")
)
}
# Colors shared by all figures.
colors <- c(
bars = "#2a78d6",
zero = "#8c8b86",
mean = "#1b1b1b",
warned = "#d6542a"
)
theme_benchmark <- function() {
theme_minimal(base_size = 11) +
theme(
plot.title.position = "plot",
panel.grid.minor = element_blank(),
panel.spacing = grid::unit(0.8, "lines"),
strip.text.y = element_text(angle = 0, hjust = 0),
legend.position = "bottom"
)
}
#' @title Histograms of differences
#' @description Plot the distribution of estimate minus target over
#' replications, with one panel per subgroup level (rows) and per
#' combination of `columns`. All panels share the x axis. A solid gray
#' line marks zero, and a dashed line marks the mean of each panel.
#' Replications whose estimate is `NA` are dropped.
#' @param estimates The `estimates` element of the output of
#' `run_benchmark()`.
#' @param columns Character vector of columns of `estimates` that define
#' the columns of panels.
#' @param xlab Label of the x axis.
#' @return A `ggplot` object.
#' @examples
#' colon <- example_colon()
#' variables <- unique(colon$summary$variable)
#' replication <- function(method) {
#' sampled <- method$sample(colon$patient, colon$summary)
#' achieved <- group_analysis_summary(sampled, variables)
#' list(estimates = compare_summary(colon$summary, achieved), runs = NULL)
#' }
#' results <- run_benchmark(benchmark_methods(), reps = 20L, replication)
#' plot_differences(results$estimates)
plot_differences <- function(
estimates,
columns = "method",
xlab = "Hazard ratio: estimate minus target"
) {
estimates <- estimates[!is.na(estimates$difference), ]
panels <- c("subgroup", columns)
means <- stats::aggregate(
estimates["difference"],
by = estimates[panels],
FUN = mean
)
ggplot(estimates, aes(x = difference)) +
geom_histogram(bins = 40L, fill = colors[["bars"]], color = NA) +
geom_vline(xintercept = 0, color = colors[["zero"]]) +
geom_vline(
aes(xintercept = difference),
data = means,
color = colors[["mean"]],
linetype = "dashed"
) +
facet_grid(stats::reformulate(columns, "subgroup"), scales = "free_y") +
labs(
title = "Solid gray line: zero. Dashed line: mean.",
x = xlab,
y = "Replications"
) +
theme_benchmark() +
theme(axis.text.y = element_blank(), panel.grid.major.y = element_blank())
}
#' @title Histograms of running times
#' @description Plot the distribution of the elapsed seconds per
#' optimization run on a log scale, with one panel per method.
#' Bars are stacked by whether the run converged or warned.
#' @param runs The `runs` element of the output of `run_benchmark()`.
#' @return A `ggplot` object.
#' @examples
#' runs <- data.frame(
#' method = in_order(rep(c("Unconstrained", "Constrained"), each = 50L)),
#' seconds = stats::rlnorm(100L),
#' warned = stats::runif(100L) < 0.1
#' )
#' plot_seconds(runs)
plot_seconds <- function(runs) {
runs$status <- factor(
ifelse(runs$warned, "Warned", "Converged"),
levels = c("Converged", "Warned")
)
ggplot(runs, aes(x = seconds, fill = status)) +
geom_histogram(bins = 40L, position = "stack", color = NA) +
facet_grid(method ~ ., scales = "free_y") +
scale_x_log10() +
scale_fill_manual(
values = c(Converged = colors[["bars"]], Warned = colors[["warned"]]),
drop = FALSE,
name = NULL
) +
labs(
x = "Elapsed seconds per optimization run (log scale)",
y = "Runs"
) +
theme_benchmark()
}
#' @title Table of convergence
#' @description Count the optimization runs of each method and the
#' fraction that warned that the loss did not fall below the tolerance.
#' @param runs The `runs` element of the output of `run_benchmark()`.
#' @return A `knitr_kable` table.
#' @examples
#' runs <- data.frame(
#' method = in_order(rep(c("Unconstrained", "Constrained"), each = 4L)),
#' seconds = 1,
#' warned = c(FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE)
#' )
#' table_convergence(runs)
table_convergence <- function(runs) {
counts <- stats::aggregate(
warned ~ method,
data = runs,
FUN = \(warned) c(length(warned), mean(warned))
)
knitr::kable(
data.frame(
Method = counts$method,
Runs = counts$warned[, 1L],
`Fraction warned` = format_number(counts$warned[, 2L]),
check.names = FALSE
),
align = c("l", "r", "r"),
row.names = FALSE
)
}Show code
# Prognostic hazard ratios of one subgroup variable: the exponentials of
# the main effect coefficients of the subgroup in the Cox model
# Surv(time, event) ~ treatment * level, with 95% Wald confidence
# intervals. levels are the levels of the subgroup variable, and the first
# is the reference. Returns one row per non-reference level, with NA if
# the model cannot be fit.
prognostic_fit <- function(data, variable, levels) {
data$level <- factor(as.character(data[[variable]]), levels = levels)
names <- paste0("level", levels[-1L])
bounds <- tryCatch(
{
fit <- survival::coxph(
survival::Surv(time, event) ~ treatment * level,
data = data,
ties = "efron"
)
cbind(stats::coef(fit), stats::confint(fit))[names, , drop = FALSE]
},
error = \(error) matrix(NA_real_, length(names), 3L),
warning = \(warning) matrix(NA_real_, length(names), 3L)
)
data.frame(
subgroup = paste0(variable, ": ", levels[-1L], " vs ", levels[1L]),
estimate = exp(bounds[, 1L]),
lower = exp(bounds[, 2L]),
upper = exp(bounds[, 3L])
)
}
# Prognostic hazard ratios of every subgroup variable in summary.
prognostic_table <- function(data, summary) {
variables <- unique(summary$variable)
rows <- lapply(variables, \(variable) {
levels <- summary$level[summary$variable == variable]
prognostic_fit(data, variable, levels)
})
do.call(rbind, rows)
}
# Pair the prognostic hazard ratios of a dataset with the true ones.
compare_prognostic <- function(data, stage, example) {
estimates <- prognostic_table(data, example$summary)
data.frame(
stage = stage,
subgroup = example$truth$subgroup,
target = example$truth$estimate,
estimate = estimates$estimate[
match(example$truth$subgroup, estimates$subgroup)
]
)
}
# One replication of one method, following steps 1 to 4 of the Design
# section. Returns estimates (one row per stage and subgroup level) and
# runs (one row).
replication <- function(method, example) {
sampled <- method$sample(example$patient, example$summary)
run <- optimize_once(
method$optimize,
sampled,
example$summary,
iterations,
tolerance
)
list(
estimates = rbind(
compare_prognostic(sampled, "Sampled", example),
compare_prognostic(run$optimized, "Optimized", example)
),
runs = data.frame(seconds = run$seconds, warned = run$warned)
)
}
show_truth <- function(truth) {
knitr::kable(
data.frame(
Subgroup = truth$subgroup,
`Prognostic HR (95% CI)` = paste0(
format_number(truth$estimate),
" (", format_number(truth$lower), ", ",
format_number(truth$upper), ")"
),
check.names = FALSE
),
align = c("l", "r"),
row.names = FALSE
)
}Colon cancer example
The true subgroups come from survival::colon, with the
same patients and the same subgroup definitions as
group_example_patient() and
group_example_summary().
data <- survival::colon
data <- data[data$etype == 2 & data$rx %in% c("Obs", "Lev+5FU"), ]
colon <- example_colon()
patient <- colon$patient
summary <- colon$summary
true_subgroups <- patient
true_subgroups$age <- factor(
ifelse(data$age < 60, "under 60", "60 or over"),
levels = c("under 60", "60 or over")
)
true_subgroups$node4 <- factor(
ifelse(data$node4 == 1, "yes", "no"),
levels = c("no", "yes")
)
true_subgroups$sex <- factor(
ifelse(data$sex == 1, "male", "female"),
levels = c("female", "male")
)
# The true subgroups must reproduce the summary statistics exactly.
true_statistics <- group_analysis_summary(true_subgroups, unique(summary$variable))
stopifnot(
identical(true_statistics$patients, summary$patients),
all(true_statistics$events == summary$events)
)
colon$truth <- prognostic_table(true_subgroups, summary)The true prognostic hazard ratios are:
| Subgroup | Prognostic HR (95% CI) |
|---|---|
| age: 60 or over vs under 60 | 1.285 (0.947, 1.743) |
| node4: yes vs no | 2.459 (1.798, 3.362) |
| sex: male vs female | 1.076 (0.794, 1.458) |
We run 1000 replications of each method.
set.seed(1)
colon_results <- run_benchmark(
benchmark_methods(),
reps = reps,
replication = \(method) replication(method, colon)
)Estimates
The model could not be fit in 1 combinations of replicate dataset and subgroup level, which are excluded from the figure.

Colon cancer example: prognostic hazard ratio of each subgroup level, replicate minus truth, for the sampled and optimized datasets of each method. The solid gray line marks zero, and the dashed line marks the mean.
Primary biliary cholangitis example
This example is a stress test: its prognostic hazard ratios are more
extreme than those of most subgroups in published forest plots. The
patient-level data, the true subgroups, and the summary statistics all
come from survival::pbc.
data <- survival::pbc
data <- data[!is.na(data$trt), ] # The 312 randomized patients.
patient <- group_data_patient(
tibble::tibble(
arm = ifelse(data$trt == 1, "treatment", "control"), # 1 = D-penicillamine.
time = as.numeric(data$time),
event = as.integer(data$status == 2) # 2 = death, 1 = transplant.
),
arm = "arm",
treatment = "treatment",
time = "time",
event = "event"
)
yes_no <- \(x) factor(ifelse(x, "yes", "no"), levels = c("no", "yes"))
true_subgroups <- patient
true_subgroups$hepatomegaly <- yes_no(data$hepato == 1)
true_subgroups$spiders <- yes_no(data$spiders == 1)
true_subgroups$edema <- yes_no(data$edema > 0)
true_subgroups$stage4 <- yes_no(data$stage == 4)
variables <- c("hepatomegaly", "spiders", "edema", "stage4")
summary <- group_data_summary(
group_analysis_summary(true_subgroups, variables),
variable = "variable",
level = "level",
patients = "patients",
events = "events",
hazard_ratio = "hazard_ratio"
)
pbc <- list(patient = patient, summary = summary)
pbc$truth <- prognostic_table(true_subgroups, summary)The true prognostic hazard ratios are:
| Subgroup | Prognostic HR (95% CI) |
|---|---|
| hepatomegaly: yes vs no | 3.466 (1.948, 6.168) |
| spiders: yes vs no | 2.147 (1.274, 3.618) |
| edema: yes vs no | 4.210 (2.331, 7.602) |
| stage4: yes vs no | 2.966 (1.785, 4.929) |
We run 1000 replications of each method.
set.seed(2)
pbc_results <- run_benchmark(
benchmark_methods(),
reps = reps,
replication = \(method) replication(method, pbc)
)Estimates
The model could not be fit in 1 combinations of replicate dataset and subgroup level, which are excluded from the figure.

Primary biliary cholangitis example: prognostic hazard ratio of each subgroup level, replicate minus truth, for the sampled and optimized datasets of each method. The solid gray line marks zero, and the dashed line marks the mean.
Simulated example
simulate_dataset() simulates one dataset, computes the
summary statistics of its true subgroups, and fits the model to the true
subgroups.
simulate_dataset <- function(n) {
levels <- c("low", "middle", "high")
log_prognostic <- log(c(1, 1.5, 2))
log_treatment <- log(c(0.5, 0.7, 0.9))
treatment <- stats::rbinom(n, 1L, 0.5)
x <- sample.int(3L, n, replace = TRUE, prob = c(0.3, 0.3, 0.4))
rate <- 0.1 * exp(log_prognostic[x] + log_treatment[x] * treatment)
event_time <- stats::rexp(n, rate)
censor_time <- stats::runif(n, 0, 20)
patient <- group_data_patient(
tibble::tibble(
arm = ifelse(treatment == 1L, "treatment", "control"),
time = pmin(event_time, censor_time),
event = as.integer(event_time <= censor_time)
),
arm = "arm",
treatment = "treatment",
time = "time",
event = "event"
)
true_subgroups <- patient
true_subgroups$group <- factor(levels[x], levels = levels)
summary <- group_data_summary(
group_analysis_summary(true_subgroups, "group"),
variable = "variable",
level = "level",
patients = "patients",
events = "events",
hazard_ratio = "hazard_ratio"
)
list(
patient = patient,
summary = summary,
truth = prognostic_table(true_subgroups, summary)
)
}We simulate 50 datasets and run 20 replications of each method on each. Each replicate is compared with the true prognostic hazard ratios of its own simulated dataset, and the figures and the table pool all simulated datasets.
set.seed(3)
simulated_results <- lapply(seq_len(simulated_datasets), \(dataset) {
example <- simulate_dataset(simulated_patients)
results <- run_benchmark(
benchmark_methods(),
reps = simulated_reps,
replication = \(method) replication(method, example)
)
list(
estimates = cbind(dataset = dataset, results$estimates),
runs = results$runs
)
})
simulated_estimates <- do.call(rbind, lapply(simulated_results, \(x) x$estimates))
simulated_runs <- do.call(rbind, lapply(simulated_results, \(x) x$runs))



