Time-Varying Condition Comparisons

knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(gp3sequences)

Model target

fit_time_varying_sequence_model() estimates the probability of a declared state or transition over aligned sequence time. It uses group-specific smooths and can include a participant random-effect smooth. The model concerns a predeclared structural outcome, not an unobserved psychological state.

Synthetic repeated sequences

set.seed(1)
participants <- paste0("p", 1:24)
x <- do.call(
  rbind,
  lapply(seq_along(participants), function(i) {
    time <- 1:12
    group <- if (i <= 12L) "control" else "treatment"
    linear <-
      -0.4 +
      0.06 * time +
      0.35 * (group == "treatment") * sin(time / 3)

    data.frame(
      participant_id = participants[i],
      sequence_id = participants[i],
      sequence_order = time,
      group = group,
      state = ifelse(
        stats::runif(length(time)) < stats::plogis(linear),
        "A",
        "B"
      ),
      stringsAsFactors = FALSE
    )
  })
)

Fit and inspect

if (requireNamespace("mgcv", quietly = TRUE)) {
  model <- fit_time_varying_sequence_model(
    x,
    group_col = "group",
    participant_id_col = "participant_id",
    target_state = "A",
    k = 5L
  )
  model_summary <- summarise_time_varying_sequence_model(model)
  model_summary$metadata
  model_summary$parametric_terms
  model_summary$smooth_terms
}

Predictions

if (requireNamespace("mgcv", quietly = TRUE)) {
  predictions <- predict_time_varying_sequence_model(
    model,
    time = seq(1, 12, length.out = 60L),
    level = 0.95
  )
  head(predictions)
}
if (requireNamespace("mgcv", quietly = TRUE)) {
  plot_time_varying_sequence_model(model)
}

Transition outcomes

Use outcome = "transition" together with from_state and to_state to model a predeclared transition. The time coordinate refers to the origin position.

Interpretation

Pointwise intervals describe uncertainty conditional on the fitted model. A time-varying association is not automatically a causal condition effect. Causal language requires valid assignment, implementation, estimand definition, and an analysis aligned with the experimental design.



Try the gp3sequences package in your browser

Any scripts or data that you put into this service are public.

gp3sequences documentation built on Aug. 23, 2026, 5:10 p.m.