% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/simswc.R
\name{simswc}
\alias{simswc}
\title{Simulate longitudinal survival data with three-way treatment switching}
\usage{
simswc(n, n_visit, base_cov = paste0("L", 1:6), trt_prob = 0.5,
  param_tdcov, param_tdcov2, param_sw, param_haz, param_cens = NULL,
  study_end = n_visit, lagk = FALSE, param_select = NULL,
  p_pick_CE = 0.5, true_hr = TRUE, truth_n = 1e+05)
}
\arguments{
\item{n}{Integer sample size. The current implementation requires an integer
greater than 49.}

\item{n_visit}{Integer number of planned discrete visits, \eqn{K}. The visit
indices in the wide data are \verb{0, ..., n_visit - 1}, and the long-format
intervals are initially \verb{[0,1), [1,2), ...}.}

\item{base_cov}{Character vector specifying which baseline covariates are
included in the simulator's linear predictors and used to define strata for
baseline randomization. Must be a non-empty subset of
\code{c("L1", "L2", "L3", "L4", "L5", "L6")}. Coefficients in all parameter
vectors must follow this exact order.}

\item{trt_prob}{Numeric scalar in \verb{(0, 1)}. Target probability of assignment
to baseline experimental treatment \eqn{A_0 = 1} within each stratum formed
by \code{base_cov}.}

\item{param_tdcov}{Numeric vector of length \code{length(base_cov) + 3} giving the
coefficients \eqn{\eta} for the binary time-varying confounder model for
\code{X}. If \code{p = length(base_cov)}, the required order is:
\itemize{
\item \verb{[1]}: intercept \eqn{\eta_0};
\item \verb{[2:(p+1)]}: baseline-covariate coefficients
\eqn{\eta_L}, in the same order as \code{base_cov};
\item \verb{[p+2]}: coefficient for prior treatment \eqn{A_{k-1}}
\eqn{\eta_A};
\item \verb{[p+3]}: coefficient for prior binary confounder
\eqn{X_{k-1}}, \eqn{\eta_X}.
}}

\item{param_tdcov2}{Numeric vector of length \code{length(base_cov) + 3} giving
the coefficients \eqn{\alpha} for the continuous time-varying confounder
mean model for \code{U}. If \code{p = length(base_cov)}, the required order is:
\itemize{
\item \verb{[1]}: intercept \eqn{\alpha_0};
\item \verb{[2:(p+1)]}: baseline-covariate coefficients
\eqn{\alpha_L}, in the same order as \code{base_cov};
\item \verb{[p+2]}: coefficient for prior treatment \eqn{A_{k-1}},
\eqn{\alpha_A};
\item \verb{[p+3]}: coefficient for prior continuous confounder
\eqn{U_{k-1}}, \eqn{\alpha_U}.
}}

\item{param_sw}{Numeric vector of length \code{length(base_cov) + 4} giving the
coefficients \eqn{\delta} for the generic treatment-switch model. If
\code{p = length(base_cov)}, the required order is:
\itemize{
\item \verb{[1]}: intercept \eqn{\delta_0};
\item \verb{[2:(p+1)]}: baseline-covariate coefficients
\eqn{\delta_L}, in the same order as \code{base_cov};
\item \verb{[p+2]}: coefficient for prior treatment \eqn{A_{k-1}},
\eqn{\delta_A};
\item \verb{[p+3]}: coefficient for current binary confounder \eqn{X_k},
\eqn{\delta_X};
\item \verb{[p+4]}: coefficient for current continuous confounder \eqn{U_k},
\eqn{\delta_U}.
}}

\item{param_haz}{Numeric vector of length \code{length(base_cov) + 7} specifying
the piecewise exponential survival model. If \code{p = length(base_cov)}, the
required order is:
\itemize{
\item \verb{[1]}: baseline hazard scale \eqn{\lambda_0}. This is a hazard
scale, not a log-hazard coefficient, and should be positive;
\item \verb{[2]}: log hazard ratio for current treatment \eqn{A_k},
\eqn{\beta_A};
\item \verb{[3:(p+2)]}: baseline-covariate log hazard ratios
\eqn{\beta_L}, in the same order as \code{base_cov};
\item \verb{[p+3]}: log hazard ratio for current binary confounder
\eqn{X_k}, \eqn{\beta_X};
\item \verb{[p+4]}: log hazard ratio for current continuous confounder
\eqn{U_k}, \eqn{\beta_U};
\item \verb{[p+5]}: log hazard ratio for \code{ES} status,
\eqn{\beta_{ES}};
\item \verb{[p+6]}: log hazard ratio for \code{CE} status,
\eqn{\beta_{CE}};
\item \verb{[p+7]}: log hazard ratio for \code{CS} status,
\eqn{\beta_{CS}}.
}}

\item{param_cens}{Optional numeric vector of length \code{length(base_cov) + 4}
giving the coefficients \eqn{\gamma} for the discrete-time random
censoring model. If \code{NULL}, no random censoring is generated beyond the
administrative censoring mechanism. If \code{p = length(base_cov)}, the required
order is:
\itemize{
\item \verb{[1]}: intercept \eqn{\gamma_0};
\item \verb{[2:(p+1)]}: baseline-covariate coefficients
\eqn{\gamma_L}, in the same order as \code{base_cov};
\item \verb{[p+2]}: coefficient for current treatment \eqn{A_k},
\eqn{\gamma_A};
\item \verb{[p+3]}: coefficient for current binary confounder \eqn{X_k},
\eqn{\gamma_X};
\item \verb{[p+4]}: coefficient for current continuous confounder \eqn{U_k},
\eqn{\gamma_U}.
}}

\item{study_end}{Numeric scalar giving the nominal administrative study-end
time. Must be between \code{2} and \code{n_visit}. The actual administrative
censoring time returned as \code{C.a} is \code{study_end - T_e}, where \code{T_e} is a
randomly sampled integer from \code{0:floor(n_visit / 3)}.}

\item{lagk}{Logical. If \code{TRUE}, add lagged versions of \code{A}, \code{X}, and \code{U} up
to three prior visits and one-step future versions of \code{X} and \code{U} to the
long-format output. If \code{FALSE}, these auxiliary lag/lead variables are not
added.}

\item{param_select}{Optional numeric vector of length 3 controlling the
\code{CE} versus \code{CS} destination model among newly switching control-arm
subjects. The required order is:
\itemize{
\item \verb{[1]}: intercept \eqn{\xi_0};
\item \verb{[2]}: coefficient for current \eqn{X_k}, \eqn{\xi_X};
\item \verb{[3]}: coefficient for current \eqn{U_k}, \eqn{\xi_U}.
}
If \code{NULL}, \code{p_pick_CE} is used instead.}

\item{p_pick_CE}{Numeric scalar in \verb{[0, 1]}. Probability that a newly
switching control-arm subject switches to experimental therapy (\code{CE})
rather than subsequent therapy (\code{CS}) when \code{param_select = NULL}.}

\item{true_hr}{Logical. If \code{TRUE}, compute an approximate Monte Carlo
benchmark for the sustained always-experimental versus always-control
comparison using \code{truth_n} simulated subjects per sustained regime. This
benchmark ignores switching and uses the non-switch components of the
longitudinal confounder and hazard models.}

\item{truth_n}{Non-negative integer Monte Carlo sample size used only when
\code{true_hr = TRUE}. Set \code{true_hr = FALSE} or \code{truth_n = 0} to skip this
potentially time-consuming benchmark.}
}
\value{
A list with components:
\itemize{
\item \code{dat}: Subject-level wide-format data. It contains \code{id}, selected
baseline covariates, visit-indexed matrices expanded into columns for
\code{X}, \code{U}, \code{A}, \code{V}, \code{S_ES}, \code{S_CE}, and \code{S_CS}, observed event/censoring
information (\code{T.obs}, \code{D.obs}), observed switch time \code{T.w}, administrative
censoring time \code{C.a}, and observed switch type \code{type_sw} (\code{1 = ES},
\code{2 = CE}, \code{3 = CS}, \verb{NA = no observed switch before exit}).
\item \code{dat_long}: Counting-process long-format data derived from \code{dat},
with one row per subject-interval while the subject is under observation.
It includes \code{t.start}, \code{t.stop}, \code{event}, \code{C}, selected baseline
covariates, \code{A}, \code{V}, \code{X}, \code{U}, and \code{S_ES}/\code{S_CE}/\code{S_CS}. If \code{lagk = TRUE},
it also includes the lag/lead variables described above.
\item \code{C}: An \code{n} by \code{n_visit + 1} matrix containing the cumulative
censoring process after combining random and administrative censoring.
\item \code{stats}: Named summary statistics: \code{init_trt}, the proportion
randomized to experimental treatment; \code{switched}, the proportion with an
observed switch before exit; \code{prop_ES}, \code{prop_CE}, and \code{prop_CS}, the
proportions of switch types among switchers; and \code{prop_event}, the
observed event proportion.
\item \code{true_sdiff}: If \code{true_hr = TRUE} and \code{truth_n > 0}, a list containing
an approximate sustained-regime benchmark, including a fitted
\code{survival::survfit} object, time grid \code{t}, survival curves \code{surv0} and
\code{surv1}, an approximate Cox hazard ratio \code{cHR}, survival difference
\code{surv_diff}, and the simulated benchmark datasets \code{dat_A0} and \code{dat_A1}.
Otherwise \code{NULL}.
}
}
\description{
\code{simswc()} simulates a two-arm randomized clinical-trial-like longitudinal
survival dataset with a three-way post-randomization treatment swich
process. It is intended to generate data for evaluating and demonstrating
multi-regime marginal structural Cox model \code{\link[=multimsm]{multimsm()}}.

Follow-up is represented on a discrete visit grid
\eqn{k = 0, 1, \ldots, K - 1}, where \code{K = n_visit}. Each subject is
randomized at baseline to experimental treatment \eqn{A_0 = 1} or control
treatment \eqn{A_0 = 0}. During follow-up, subjects may experience at most
one absorbing treatment switch:

\itemize{
\item \code{ES}: randomized experimental \eqn{\rightarrow} subsequent therapy;
\item \code{CE}: randomized control \eqn{\rightarrow} experimental crossover;
\item \code{CS}: randomized control \eqn{\rightarrow} subsequent therapy.
}

The simulator generates baseline covariates, two time-varying confounders
(\code{X} and \code{U}), a generic switch process \code{V}, switch-type indicators
\code{S_ES}, \code{S_CE}, and \code{S_CS}, optional random censoring, and a survival outcome
from a piecewise exponential hazard model. The output includes both
subject-level wide-format data and counting-process long-format data suitable
for Cox modeling and for the package's multi-regime MSM workflow.
}
\details{
Let \eqn{L_i} denote the vector of selected baseline covariates named in
\code{base_cov}. The simulator first generates six possible baseline covariates:

\itemize{
\item \code{L1}: Binary age group indicator,
\eqn{L_1 \sim \mathrm{Bernoulli}(0.3)}.
\item \code{L2}: Three-level risk group taking values \code{0}, \code{1}, and \code{2} with
probabilities \code{0.60}, \code{0.35}, and \code{0.05}, respectively.
\item \code{L3}: Binary baseline metastasis/progression-like indicator,
\eqn{L_3 \sim \mathrm{Bernoulli}(0.1)}.
\item \code{L4}: Continuous tumor-size-like marker,
\eqn{L_4 \sim N(60, 35^2)}.
\item \code{L5}: Binary biomarker indicator,
\eqn{L_5 \sim \mathrm{Bernoulli}(0.8)}.
\item \code{L6}: Binary prior-treatment indicator,
\eqn{L_6 \sim \mathrm{Bernoulli}(0.6)}.
}

Only the variables included in \code{base_cov} are used in the treatment,
confounder, switch, censoring, and hazard linear predictors, and only these
selected baseline covariates are returned in the simulated datasets.

Baseline treatment is assigned by stratified randomization within the
interaction strata formed by \code{base_cov}; within each stratum, approximately
\code{trt_prob} of subjects are assigned to \eqn{A_0 = 1}. Because \code{base_cov}
defines both the model covariate vector and the randomization strata, using a
continuous variable such as \code{L4} may create many small strata. In practical
simulation studies, it is often preferable to stratify on categorical or binary
baseline covariates, for example \code{base_cov = c("L1", "L3")}.

The time-varying binary confounder \code{X} is initialized as \eqn{X_0 = 0} and is
made absorbing by construction. For \eqn{k = 1, \ldots, K - 1},

\deqn{
\Pr(\widetilde X_{ik}=1 \mid H_{i,k-1}) =
\operatorname{expit}\{\eta_0 + \eta_L^\top L_i +
\eta_A A_{i,k-1} + \eta_X X_{i,k-1}\},
}

and the stored value is

\deqn{X_{ik} = \max(X_{i,k-1}, \widetilde X_{ik}).}

The continuous time-varying confounder \code{U} is initialized as
\eqn{U_0 \sim N(0,1)}. For \eqn{k = 1, \ldots, K - 1},

\deqn{
U_{ik} \sim N(\mu_{ik}, 1), \quad
\mu_{ik} =
\alpha_0 + \alpha_L^\top L_i +
\alpha_A A_{i,k-1} + \alpha_U U_{i,k-1}.
}

The generic switch indicator \code{V} is initialized as \eqn{V_0 = 0}. Among
subjects who have not yet switched, the probability of a new switch at visit
\eqn{k} is

\deqn{
\Pr(V_{ik}=1 \mid V_{i,k-1}=0, H_{ik}) =
\operatorname{expit}\{\delta_0 + \delta_L^\top L_i +
\delta_A A_{i,k-1} + \delta_X X_{ik} + \delta_U U_{ik}\}.
}

Once a subject switches, \code{V} remains equal to 1. The switch destination is then
assigned as follows:

\itemize{
\item if \eqn{A_{i0}=1}, the subject switches to \code{ES}; \code{S_ES} is set to 1
from that visit onward and \code{A} is set to 0 thereafter to represent being
off the original experimental-treatment indicator and on subsequent
therapy;
\item if \eqn{A_{i0}=0}, the subject switches either to \code{CE} or to \code{CS};
under \code{CE}, \code{S_CE} is set to 1 and \code{A} is set to 1 thereafter; under \code{CS},
\code{S_CS} is set to 1 and \code{A} remains 0 thereafter.
}

If \code{param_select = NULL}, the control-arm switch destination is chosen with
fixed probability \code{p_pick_CE} for \code{CE} and \code{1 - p_pick_CE} for \code{CS}. If
\code{param_select} is supplied, the probability of \code{CE} among newly switching
control-arm subjects is

\deqn{
\Pr(\mathrm{CE}_{ik}=1 \mid \mathrm{new\ switch}, A_{i0}=0) =
\operatorname{expit}\{\xi_0 + \xi_X X_{ik} + \xi_U U_{ik}\}.
}

The event time is generated from a piecewise exponential model. For interval
\eqn{[k, k+1)}, where \eqn{k = 0,\ldots,K-1}, the internal column index is
\eqn{m = k + 1}, and the interval-specific hazard is

\deqn{
\lambda_{ik} =
\{\lambda_0 \exp(0.1m)\}
\exp\{\beta_A A_{ik} + \beta_L^\top L_i +
\beta_X X_{ik} + \beta_U U_{ik} +
\beta_{ES} S^{ES}_{ik} +
\beta_{CE} S^{CE}_{ik} +
\beta_{CS} S^{CS}_{ik}\}.
}

Conditional on the interval covariates, an exponential waiting time with rate
\eqn{\lambda_{ik}} is drawn. If the waiting time is less than 1, the event is
placed inside that interval at exact continuous time \eqn{k + T^\ast};
otherwise simulation proceeds to the next interval.

If \code{param_cens} is supplied, random right censoring is generated in discrete
time. At the end of interval \eqn{k}, among subjects not yet randomly
censored,

\deqn{
\Pr(C_{i,k+1}=1 \mid C_{ik}=0, H_{ik}) =
\operatorname{expit}\{\gamma_0 + \gamma_L^\top L_i +
\gamma_A A_{ik} + \gamma_X X_{ik} + \gamma_U U_{ik}\}.
}

If \code{param_cens = NULL}, no additional random censoring is generated. In all
cases, the simulator also applies an administrative censoring time
\code{C.a = study_end - T_e}, where \code{T_e} is sampled uniformly from the integers
\code{0:floor(n_visit / 3)}. The observed time is the minimum of event time,
random censoring time, and administrative censoring time.

The long-format output uses start-stop counting-process intervals. The
terminal event time is kept as a continuous time when the event occurs inside
an interval. If \code{lagk = TRUE}, the long-format data also include
\code{Alag1}-\code{Alag3}, \code{Xlag1}-\code{Xlag3}, \code{Ulag1}-\code{Ulag3}, and one-step leads
\code{Xnext1} and \code{Unext1}.

For the revised triplet-input \code{\link[=multimsm]{multimsm()}} interface, the simulation output
can be converted by defining \code{rand} as the subject-level baseline treatment
\code{A.0}, \code{cross = S_CE}, and \code{subseq = pmax(S_ES, S_CS)}.
}
\examples{
set.seed(123)

sim_obj <- simswc(
  n = 200,
  n_visit = 8,
  base_cov = c("L1", "L3"),
  trt_prob = 0.5,
  param_tdcov  = c(-1.5, 0.3, 0.3, -0.2, 0.5),
  param_tdcov2 = c( 0.05, 0.2, 0.2, -0.2, 0.7),
  param_sw     = c(-3.0, 0.4, 0.4, -0.3, 0.3, 0.8),
  param_haz    = c(0.1, log(0.8), log(1.1), log(1.1),
                   log(1.4), log(1.4), log(1.3), log(1), log(0.9)),
  param_cens   = NULL,
  param_select = c(0, 0.5, 0.25),
  lagk = TRUE,
  true_hr = FALSE
)

head(sim_obj$dat_long)
sim_obj$stats

## Convert to the triplet interface used by multimsm().
dat <- sim_obj$dat_long
dat$rand <- stats::ave(dat$A, dat$id, FUN = function(x) rep(x[1], length(x)))
dat$cross <- dat$S_CE
dat$subseq <- pmax(dat$S_ES, dat$S_CS)

table(dat$rand, dat$cross, dat$subseq)

}
\references{
Keogh RH, Seaman SR, Gran JM, Vansteelandt S. Simulating longitudinal data
from marginal structural models using the additive hazard model.
\emph{Biometrical Journal}. 2021;63:1526-1541.
}
