Learn R Programming

TrialEmulation (version 0.0.4.2)

fit_msm: Fit the marginal structural model for the sequence of emulated trials

Description

[Experimental]

Usage

fit_msm(
  object,
  weight_cols = c("weight", "sample_weight"),
  modify_weights = NULL
)

# S4 method for trial_sequence fit_msm( object, weight_cols = c("weight", "sample_weight"), modify_weights = NULL )

Value

A modified trial_sequence object with updated outcome_model slot.

Arguments

object

A trial_sequence object

weight_cols

character vector of column names in expanded outcome dataset, ie outcome_data(object). If multiple columns are specified, the element wise product will be used. Specify NULL if no weight columns should be used.

modify_weights

a function to transform the weights (or NULL for no transformation). Must take a numeric vector of weights and a vector of positive, finite weights of the same length. See examples for some possible function definitions.

Before the outcome marginal structural model can be fit, the outcome model must be specified with set_outcome_model() and the data must be expanded into the trial sequence with expand_trials().

The model is fit based on the model_fitter specified in set_outcome_model using the internal fit_outcome_model method.

Examples

Run this code
trial_seq_object <- trial_sequence("ITT") |>
  set_data(data_censored) |>
  set_outcome_model(
    adjustment_terms = ~age_s,
    followup_time_terms = ~ stats::poly(followup_time, degree = 2)
  ) |>
  set_expansion_options(output = save_to_datatable(), chunk_size = 500) |>
  expand_trials() |>
  load_expanded_data()

fit_msm(trial_seq_object)

# Using modify_weights functions ----

# returns a function that truncates weights to limits
limit_weight <- function(lower_limit, upper_limit) {
  function(w) {
    w[w > upper_limit] <- upper_limit
    w[w < lower_limit] <- lower_limit
    w
  }
}

# calculate 1st and 99th percentile limits and truncate
p99_weight <- function(w) {
  p99 <- quantile(w, prob = c(0.01, 0.99), type = 1)
  limit_weight(p99[1], p99[2])(w)
}

# set all weights to 1
all_ones <- function(w) {
  rep(1, length(w))
}

fit_msm(trial_seq_object, modify_weights = limit_weight(0.01, 4))
fit_msm(trial_seq_object, modify_weights = p99_weight)

Run the code above in your browser using DataLab