% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/longitudinal_grmtree.R
\name{longitudinal_grmtree}
\alias{longitudinal_grmtree}
\title{Fit a Longitudinal Graded Response Model Tree for Response Shift Detection}
\usage{
longitudinal_grmtree(
  formula,
  data,
  n_items = NULL,
  na.action = na.omit,
  control = grmtree.control(),
  mtry = NULL,
  ...
)
}
\arguments{
\item{formula}{A formula specifying the model structure with a wide-format
response matrix on the left-hand side and partitioning variables on the
right-hand side (e.g., \code{resp_wide ~ age + sex + comorbidity_count}).
The response matrix must have \code{2 * n_items} columns: the first
\code{n_items} columns are Time 1 (T1) responses and the next
\code{n_items} columns are Time 2 (T2) responses for the same items.}

\item{data}{A data frame containing the variables in the formula. Must
include the response matrix as a matrix-valued column (created via
\code{data$resp_wide <- as.matrix(...)}) and all partitioning variables
as separate columns.}

\item{n_items}{Integer specifying the number of items per time point. If
\code{NULL} (default), automatically detected as half the number of
columns in the response matrix. Must satisfy
\code{ncol(response) == 2 * n_items}.}

\item{na.action}{How to handle missing values. Default is \code{na.omit},
which removes rows with any missing values in the response matrix or
partitioning variables.}

\item{control}{A list of control parameters created by
\code{\link[grmtree]{grmtree.control}}. Key parameters include:
\describe{
\item{\code{minbucket}}{Minimum number of observations in a terminal
node. Should be at least 10 times the number of free parameters per
node to ensure stable estimation. For 8 items with 5 categories each,
the constrained longitudinal GRM has approximately 40 item parameters
plus 3 latent parameters, suggesting \code{minbucket >= 200}.}
\item{\code{alpha}}{Significance level for the parameter instability
tests. Default is 0.05.}
\item{\code{p_adjust}}{Method for adjusting p-values across covariates
at each split. Options include \code{"bonferroni"} (default, applied
locally during tree construction), \code{"BH"}
(Benjamini-Hochberg, applied post-hoc with pruning), and others.
See \code{\link[grmtree]{grmtree.control}} for details.}
}}

\item{mtry}{Number of variables randomly sampled as candidates at each
split. If \code{NULL} (default), all variables are considered. Can be
used for random forest extensions.}

\item{...}{Additional arguments passed to the internal fitting function
\code{\link{longitudinal_grmfit}} and ultimately to
\code{\link[mirt]{mirt}}.}
}
\value{
An object of class \code{c("longitudinal_grmtree", "grmtree",
  "modelparty", "party")} containing the fitted tree structure. The object
inherits from \code{\link[partykit]{modelparty}} and includes:
\describe{
\item{Tree structure}{Accessible via standard \code{partykit} methods
such as \code{\link[partykit]{nodeids}},
\code{\link[partykit]{data_party}}, and indexing with \code{[[}.}
\item{Node models}{Each terminal node contains a fitted constrained
longitudinal GRM with item parameters (discrimination and thresholds),
latent trait means (\eqn{\mu_{T2}}), and latent trait covariance
matrix (\eqn{\sigma^2_{T2}}, \eqn{r_{T1,T2}}).}
\item{\code{info$n_items}}{Number of items per time point.}
\item{\code{info$model_type}}{\code{"longitudinal_grm"}.}
\item{\code{info$p_adjust}}{The p-value adjustment method used.}
\item{\code{info$call}}{The original function call.}
}
}
\description{
This function implements a tree-based longitudinal graded response model
using model-based recursive partitioning (MOB) to detect measurement
heterogeneity in patient-reported outcome measures (PROMs) measured at two
time points. The Longitudinal GRMTree extends the cross-sectional
\code{\link[grmtree]{grmtree}} to the longitudinal setting by embedding
a constrained two-factor GRM within the MOB framework. The resulting tree
identifies patient subgroups where the longitudinal measurement model
differs, providing the foundation for subgroup-specific response shift
characterization via \code{\link{rs_characterize}}.
}
\details{
\subsection{Overview}{

The Longitudinal GRMTree is a unified framework for response shift
detection that operates in two phases:

\strong{Phase 1 (this function):} Identifies patient subgroups where the
constrained longitudinal measurement model differs. The constrained model
represents the null hypothesis of no response shift (item parameters equal
across time). MOB tests whether this null model's parameters are stable
across patient covariates and recursively partitions the sample where
instability is detected.

\strong{Phase 2 (\code{\link{rs_characterize}}):} Within each terminal
node, tests whether item parameters actually change from T1 to T2 by
comparing the constrained model to an unconstrained model using likelihood
ratio tests. This phase characterizes response shift at the item level,
classifying changes as recalibration, reprioritization, or both.
}

\subsection{Constrained Two-Factor Longitudinal GRM}{

Let \eqn{Y_{im}} denote the response of individual \eqn{i} to item \eqn{m}
at time \eqn{t}. The longitudinal GRM specifies two correlated latent
factors:

\deqn{\theta_{i,T1} \sim N(0, 1)}
\deqn{\theta_{i,T2} \sim N(\mu_{T2}, \sigma^2_{T2})}
\deqn{Cov(\theta_{i,T1}, \theta_{i,T2}) = \sigma_{12}}

For item \eqn{m} at time \eqn{t}, the graded response model is:

\deqn{P(Y_{im,t} \geq j | \theta_{i,t}) = \frac{\exp(a_{m,t}(\theta_{i,t}
- b_{mj,t}))}{1 + \exp(a_{m,t}(\theta_{i,t} - b_{mj,t}))}}

where \eqn{a_{m,t}} is the discrimination parameter and \eqn{b_{mj,t}} are
threshold parameters for item \eqn{m} at time \eqn{t}.

Under the no-response-shift constraint:
\deqn{a_{m,T1} = a_{m,T2} \quad \text{and} \quad b_{mj,T1} = b_{mj,T2}
\quad \forall m, j}

This means item parameters are identical across time, so any observed
changes in responses are attributed to true latent change (\eqn{\mu_{T2}})
rather than changes in measurement properties.
}

\subsection{The Longitudinal GRMTree Algorithm}{

\strong{Step 1: Global Model Estimation.} Fit the constrained longitudinal
GRM to all individuals at the root node, estimating item parameters
\eqn{\hat{\beta}} and latent parameters \eqn{(\mu_{T2}, \sigma^2_{T2},
\sigma_{12})} via maximum likelihood.

\strong{Step 2: Parameter Stability Testing.} For each covariate
\eqn{X_p}, compute individual score function contributions
\eqn{s(\hat{\beta}; \mathbf{y}_i)} and test whether these scores
fluctuate systematically with \eqn{X_p} using structural change tests.
The null hypothesis is that model parameters are stable across all
values of \eqn{X_p}.

\strong{Step 3: Recursive Partitioning.} If significant instability is
detected (after p-value adjustment):
\itemize{
\item Select the covariate \eqn{X_p^*} with strongest instability
\item Find the optimal split point \eqn{c^*} maximizing the partitioned
log-likelihood
\item Split the sample: \eqn{X_p^* \leq c^*} vs. \eqn{X_p^* > c^*}
}

\strong{Step 4: Recursion.} Repeat Steps 1--3 within each child node
until no significant instability remains or the minimum node size is
reached.

\strong{Step 5 (Post-hoc):} Apply \code{\link{rs_characterize}} to test
for response shift within each terminal node.
}

\subsection{Formal Model Structure}{

The fitted Longitudinal GRMTree provides a piecewise constrained
longitudinal GRM:

\deqn{P(Y_{im,t} = k | \theta_{i,t}, \mathbf{x}_i) = \sum_{b=1}^B
I(\mathbf{x}_i \in \mathcal{X}_b) \cdot P_b(Y_{im,t} = k | \theta_{i,t})}

where \eqn{B} is the number of terminal nodes, \eqn{\mathcal{X}_b} is
the covariate subspace defining terminal node \eqn{b}, and \eqn{P_b} is
the node-specific constrained longitudinal GRM. Each terminal node
contains:
\itemize{
\item Node-specific constrained item parameters (equal across T1 and T2)
\item Node-specific latent trait parameters: \eqn{\mu_{T2,b}},
\eqn{\sigma^2_{T2,b}}, \eqn{r_{T1,T2,b}}
}
}

\subsection{Interpretation}{

The tree structure identifies patient subgroups where the constrained
longitudinal measurement model differs. This can reflect:
\itemize{
\item Different item discrimination patterns across subgroups
\item Different threshold locations across subgroups
\item Different magnitudes of true latent change (\eqn{\mu_{T2}})
\item Different test-retest correlations
}

Crucially, the tree does \strong{not} directly detect response shift
(temporal change in item parameters within a subgroup). Response shift
is tested in Phase 2 using \code{\link{rs_characterize}}, which relaxes
the equality constraints within each terminal node. A tree with only one
terminal node (no split) indicates that no covariate moderates the
measurement model; it does \strong{not} imply the absence of response
shift, since \code{\link{rs_characterize}} can still detect uniform RS in
the unsplit root node.
}

\subsection{Relationship to Existing Methods}{

The Longitudinal GRMTree extends several existing approaches:
\itemize{
\item \strong{GRMTree} (Arimoro et al., 2026): Cross-sectional DIF
detection using tree-based GRM. The longitudinal extension embeds a
two-factor model instead of a single-factor model.
\item \strong{LIRTree} (Ames & Leventhal, 2021): Longitudinal
tree-based IRT using Rasch/2PL models. The GRM extension allows
item-specific discrimination parameters, which are important for
PROMs where items vary in discriminating ability.
\item \strong{Oort SEM} (Oort, 2005): Response shift detection via
structural equation modeling. The tree-based approach removes the
requirement for pre-specified subgroups.
}
}

\subsection{Practical Recommendations}{

\itemize{
\item \strong{Minimum node size:} Use at least 10--25 times the number
of free parameters per node. For \eqn{M} items with \eqn{K} response
categories, the constrained model has approximately \eqn{M(K-1) + M + 3}
parameters (\eqn{M} discriminations, \eqn{M(K-1)} thresholds, and 3
latent parameters). For 8 items with 5 categories:
\eqn{8 \times 4 + 8 + 3 = 43} parameters, suggesting
\code{minbucket = 200--400}.
\item \strong{Number of covariates:} Bonferroni correction becomes
increasingly conservative with more covariates. Consider using
\code{p_adjust = "BH"} for exploratory analyses with many covariates.
\item \strong{Sample size:} With typical PROM instruments (5--15 items),
a total sample of at least 500--1000 is recommended for adequate power
to detect meaningful splits.
\item \strong{Response matrix preparation:} Use
\code{\link{prepare_longitudinal_data}} to construct the wide-format
response matrix from separate T1 and T2 item columns.
}
}
}
\examples{
\dontshow{if (interactive()) withAutoprint(\{ # examplesIf}
library(grmtree)

  # Load the synthetic longitudinal data
  data("grmtree_long_data", package = "grmtree")

  # Prepare the wide-format response matrix
  items_t1 <- c("MOS_Listen", "MOS_Info", "MOS_Advice_Crisis", "MOS_Confide",
                "MOS_Advice_Want", "MOS_Fears", "MOS_Personal", "MOS_Understand")
  ld <- prepare_longitudinal_data(
    data = grmtree_long_data,
    items_t1 = items_t1,
    items_t2 = paste0(items_t1, "_year1"),
    covariates = c("sex", "age", "residency", "job",
                   "education", "comorbidity_count", "ever_smoker")
  )

  # Phase 1: fit the longitudinal GRM tree
  ltree <- longitudinal_grmtree(
    resp_wide ~ sex + age + residency + job +
      education + comorbidity_count + ever_smoker,
    data = ld, n_items = 8,
    control = grmtree.control(minbucket = 200)
  )

  # Print tree structure
  print(ltree)

  # Plot threshold regions
  plot(ltree, type = "regions", tnex = 2L)

  # Phase 2: characterize response shift within each subgroup
  rs <- rs_characterize(ltree, p_adjust = "fdr",
    global_p_adjust = "bonferroni")
  print(rs)

\dontshow{\}) # examplesIf}
}
\references{
Arimoro, O. I., Lix, L. M., Patten, S. B., Sawatzky, R., Sebille, V.,
Liu, J., Wiebe, S., Josephson, C. B., & Sajobi, T. T. (2025). Tree-based
latent variable model for assessing differential item functioning in
patient-reported outcome measures: a simulation study. \emph{Quality of
Life Research}. \doi{10.1007/s11136-025-04018-6}

Ames, A. J., & Leventhal, B. C. (2021). Application of a longitudinal
IRTree model: response style changes over time. \emph{Educational and
Psychological Measurement}, 81(3), 561--582.

Oort, F. J. (2005). Using structural equation modeling to detect response
shifts and true change. \emph{Quality of Life Research}, 14(3), 587--598.

Samejima, F. (1969). Estimation of latent ability using a response pattern
of graded scores. \emph{Psychometrika Monograph Supplement}, 34, 100--114.

Sprangers, M. A., & Schwartz, C. E. (1999). Integrating response shift
into health-related quality of life research. \emph{Social Science &
Medicine}, 48(11), 1507--1515.

Zeileis, A., Hothorn, T., & Hornik, K. (2008). Model-based recursive
partitioning. \emph{Journal of Computational and Graphical Statistics},
17(2), 492--514.
}
\seealso{
\code{\link{rs_characterize}} for Phase 2 response shift characterization,
\code{\link{prepare_longitudinal_data}} for data preparation,
\code{\link[grmtree]{grmtree}} for cross-sectional DIF detection,
\code{\link[grmtree]{grmtree.control}} for control parameters,
\code{\link[partykit]{mob}} for the underlying MOB framework
}
\author{
Olayinka Imisioluwa Arimoro \email{olayinka.arimoro@ucalgary.ca},
Lisa M. Lix, Tolulope T. Sajobi
}
