prepare_data: Prepare Data for Multistate Analysis

View source: R/prepare_data.R

prepare_dataR Documentation

Prepare Data for Multistate Analysis

Description

Converts one-row-per-subject wide data into validated, long-form sojourn records for an acyclic, non-recurrent multistate process. Entry times are calendar times from a common origin; forest response times are the resulting clock-reset durations within states.

Usage

prepare_data(
  data,
  id,
  structure,
  time_map,
  censor_col,
  covariates,
  initial_state = NULL
)

Arguments

data

A data frame with one row per subject.

id

Name of the unique subject-ID column.

structure

An mstate_structure from define_multistate.

time_map

Named list mapping every noninitial state exactly once to its first and only calendar-time entry column. The initial state is excluded.

censor_col

Name of the external right-censoring column.

covariates

Explicit character vector of baseline, time-fixed predictors. Use character(0) only for preparation/AJ workflows.

initial_state

Common initial state. It must equal the unique graph root; the default is stored in structure.

Details

Delayed entry, recurrent visits, tied entry times, time-dependent covariates, and missing covariates are unsupported. Invalid trajectories produce an error; no event or interval is silently discarded. Character covariates are converted to factors in first-observed level order, and the resulting preparation schema is descriptive only. Every model fit and cross-validation refit rebuilds its schema from its own fitting rows. Subject ID, mapped entry times, censoring time, reserved long-format names, and names beginning .rfm_ cannot be predictors.

Value

An msdata data frame containing id, from, to, Tstart, Tstop, status, trans_id, duration, and retained covariates. Metadata store the graph, source-role table, predictor contract, descriptive preparation schema, counts, and observed duration support.

Limitations

The input must contain one row per subject, one common initial state at time zero, and at most one exact entry time per noninitial state. Left truncation, cycles/recurrent visits, tied or interval-censored transitions, time-dependent covariates, missing fitting covariates, events after censoring, and events after absorption are rejected. A nonabsorbed subject requires a finite censoring time strictly after the last state entry.

Examples

ms <- clinical_states()
dat <- sim_clinical_data(n = 50, structure = ms, seed = 42)
msdata <- prepare_data(
  dat, id = "ID", structure = ms,
  time_map = list(
    Responded = "time_Responded",
    Unresponded = "time_Unresponded",
    Stabilized = "time_Stabilized",
    Progressed = "time_Progressed",
    Death = "time_Death"
  ),
  censor_col = "time_censored",
  covariates = c("age", "sex", "BMI", "treatment")
)
head(msdata)


RFmstate documentation built on Sept. 10, 2026, 1:09 a.m.