Skip to contents

Estimates the average total time spent in each state over the requested follow-up period, including time accumulated across repeated visits to a state. With variables = NULL, averages over patients using their observed starting states and covariates. Supply variables to calculate averages under specified counterfactual scenarios.

Usage

avg_time(
  model,
  newdata = NULL,
  variables = NULL,
  state_sets = NULL,
  by = NULL,
  times,
  y_levels = NULL,
  absorb = NULL,
  time_map = NULL,
  baseline_time = 0,
  target_times = NULL,
  time_unit = NULL,
  id_var = NULL,
  time_var = "time",
  p_var = "yprev",
  p2_var = NULL,
  gap_var = NULL,
  time_covariates = NULL,
  include_re = FALSE,
  n_draws = 100L,
  seed = NULL,
  posterior_summary = c("mean", "median"),
  conf_level = 0.95,
  return_draws = FALSE,
  ...
)

Arguments

model

A fitted model object (e.g., vglm, orm, or blrm). For vglm models, the family must be cumulative-logit with reverse = TRUE. For orm models, the family must be logistic.

newdata

Optional data frame of standardization profiles. When supplied, every row supplies a separate starting state and set of covariates. The internal rowid column is regenerated. If NULL, uses data stored by orm_markov(), blrm_markov(), or vglm_markov() and requires exactly one complete designated starting profile per fitted patient.

variables

Optional named list of covariates to set before averaging, for example list(tx = c(0, 1)) for average times under each treatment. The default, NULL, uses each patient's observed covariates.

state_sets

States to summarize. NULL returns every state separately. A vector pools its states into one total; a named list returns one total per named state set, for example list(home = "1", hospital = c("2", "3")). Names must be unique.

by

Optional character vector of additional variables to group by after standardization. Rows missing any grouping value are omitted; an error is raised if none remain.

times

Required. The consecutive visits to include, in increasing order and each listed once, for example times = 1:30. Each value is one transition, so leaving out visits does not skip time; see the section "Choosing visits". To total time over only part of follow-up, request every visit and select the period with time_map and target_times. Numeric time variables use numeric values; factor-valued visit indices use fitted visit levels.

y_levels

A vector of state levels in fitted outcome order. Its length must agree with the fitted model's threshold count. If NULL, attempts to infer the levels from model.

absorb

The absorbing state.

time_map

Optional named numeric vector or data frame giving the elapsed time of each visit label, for example c("1" = 3, "2" = 7, "3" = 14) for visits on days 3, 7, and 14. Supplying it measures time on this elapsed-time scale instead of counting visits.

baseline_time

Elapsed time at which patients are in their starting state, used only with time_map. The default 0 means that totals are counted from time 0, when each patient is in their starting state. Set it to NULL to count from the first mapped visit instead. Supplying a value without time_map is an error.

target_times

Optional numeric vector of elapsed times, requiring time_map. Probabilities are linearly interpolated at these times and totals are the area under the resulting curve (trapezoidal rule), so the totals cover the period from the first to the last of these times. When omitted, the times are baseline_time followed by the mapped visit times, covering the whole period from the starting state to the last visit; with baseline_time = NULL, they are the mapped visit times only. Supply, for example, target_times = 7:28 to total only days 7 to 28.

time_unit

Optional label stored in output.

id_var

Name of the patient ID variable. Required for bootstrap inference and for blrm random-effect prediction. If NULL, defaults to "id"; for wrapper-fitted models, it is inferred from stored metadata. For user-supplied newdata, id_var is required only for blrm random effects. Refit bootstrap inference resamples patients by this column in the data stored on the wrapper-fitted model. For blrm models with include_re = TRUE, model$clusterInfo$name is used before the final "id" fallback when wrapper metadata is absent.

time_var

Name of the time variable in the model.

p_var

Name of the previous state variable in the model.

p2_var

Optional second previous-state variable. NULL uses a first-order Markov recursion; a non-NULL column name uses a second-order recursion.

gap_var

Optional name of the variable holding the time elapsed since the previous visit, if the model includes one. Each transition then uses the difference between consecutive values of times (the first value for the first transition), unless time_covariates contains this column, so times may skip visits. See the section "Choosing visits".

time_covariates

Optional time-varying covariate lookup table for explicit precomputed time-basis columns. Registered inline terms such as rms::rcs(time, 4) and rms::lsp(time, c(3, 7)) can be used without it.

include_re

Logical. For rmsb::blrm() fits with cluster(), include fitted random-effect draws in posterior predictions for known IDs.

n_draws

Integer number of posterior draws to sample for blrm, or NULL to use all stored draws. Defaults to 100.

seed

Optional random seed for reproducible random draw sampling.

posterior_summary

Summary of total-time posterior draws for blrm: "mean" or "median".

conf_level

Confidence level for blrm posterior intervals.

return_draws

Logical. For blrm, retain posterior time-total draws for get_draws(). Frequentist draws are retained through inferences().

...

Additional arguments reserved for future extensions.

Value

A data frame of class markov_avg_time, with state_set, any counterfactual and grouping columns, and estimate (average total time). Rows follow the order of state_sets. If supplied, time_unit is included as a label; it does not rescale time. For blrm, posterior std.error, conf.low, and conf.high are returned directly. For frequentist models, add these columns with inferences().

Details

Without time_map, each requested visit counts as one unit of time: the total for a state is the sum of its occupancy probabilities over the requested visits. For example, with times = 1:30 and daily visits, the total is the expected number of days spent in the state.

With time_map, visits are placed on the elapsed-time scale. Occupancy probabilities are joined by straight lines between the mapped times, and the total is the area under that curve. By default the curve starts at baseline_time, where each patient is in their observed starting state, so the interval before the first visit is included. For example, with visits on days 3, 7, 14, and 28 and baseline_time = 0, totals cover days 0 to 28.

inferences(method = "delta") provides analytical standard errors and confidence intervals of the form estimate plus or minus a normal quantile times the standard error. These intervals are not restricted to the possible range of time and can, for example, extend below zero. Its default vcov = "unconditional" accounts for coefficient estimation and for which patients were sampled, including their observed starting states. Use vcov = "conditional" to treat the patients' starting states and covariates as given and account only for coefficient estimation. Supplied newdata requires conditional variance. When variables sets the previous-state variable (a counterfactual starting state), the baseline starts in that state and only conditional variance is available (method = "delta", vcov = "conditional" or method = "mvn"). The analytical method supports first-order full proportional-odds frequentist models; analytical inference with by is not supported. See inferences() for additional model restrictions.

Extract the analytical covariance matrix with vcov(result). It contains a covariance for every pair of rows, including different state sets and counterfactual scenarios. Its diagonal entries are variances; their square roots are the reported standard errors.

The simulation and resampling methods of inferences() differ in which sources of uncertainty they include:

  • method = "mvn" draws model coefficients from their estimated multivariate normal distribution and keeps the patients, and therefore the distribution of starting states, fixed. It is comparable to conditional variance, so its intervals are typically narrower than the default analytical intervals.

  • method = "score_bootstrap", method = "bootstrap", and method = "fwb" (fractional weighted bootstrap) re-draw or re-weight patients, including their starting states. They are comparable to unconditional variance.

Each of these methods, and posterior summaries for blrm models, first converts every draw of occupancy probabilities into time totals and then summarizes the totals, rather than adding up separately summarized probabilities. Use get_draws() to inspect the draws when they have been retained with return_draws = TRUE.

Choosing visits

SOPs are calculated one visit at a time. The first value of times is the first transition from the starting state, and each later value is one more transition. The values set the time variable, and any time-varying covariates, for each transition; they do not say how much time passes between transitions. Leaving out visits therefore does not skip time. With daily visits, times = c(1, 7, 14) gives the probabilities after 1, 2, and 3 transitions, labelled 1, 7, and 14, instead of the probabilities on days 7 and 14. To get SOPs at selected visits, request every visit, such as times = 1:14, and keep the rows you need.

When newdata is omitted, each patient starts from their state before the first follow-up visit (first_followup_time of the fitting wrapper), so times must begin at that visit. Each row of a supplied newdata starts from its previous state at the first requested visit, which may be a later visit.

A warning is given when times leaves out visits that occur in the data the model was fitted to, is not in increasing order, or, when newdata is omitted, does not begin at the first follow-up visit. Times after the last fitted visit are allowed. There is no warning when gap_var is supplied, because each transition then uses its own elapsed time, so the visits may be spaced unevenly.

Examples

if (FALSE) { # \dontrun{
# Average over the fitted patients' observed starting states and covariates.
avg_time(fit, times = 1:30) |>
  inferences(method = "delta")

avg_time(
  fit, variables = list(tx = c(0, 1)), times = 1:30,
  state_sets = list(home = "1", hospital = c("2", "3"))
) |>
  inferences(method = "delta", vcov = "conditional")

# Visits on days 3, 7, 14, and 28; totals cover days 0 to 28.
avg_time(
  fit, times = 1:4, time_map = c("1" = 3, "2" = 7, "3" = 14, "4" = 28),
  time_unit = "days"
) |>
  inferences(method = "fwb", n_draws = 500)
} # }