% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/icc.R
\name{icc_rm_reml}
\alias{icc_rm_reml}
\alias{print.icc_rm_reml}
\alias{summary.icc_rm_reml}
\alias{print.summary.icc_rm_reml}
\title{Repeated-Measures Intraclass Correlation via REML}
\usage{
icc_rm_reml(
  data,
  response,
  subject,
  method = NULL,
  time = NULL,
  type = c("consistency", "agreement"),
  ci = FALSE,
  conf_level = 0.95,
  n_threads = getOption("matrixCorr.threads", 1L),
  ci_mode = c("auto", "raw", "logit"),
  verbose = FALSE,
  digits = 4,
  use_message = TRUE,
  interaction = FALSE,
  max_iter = 100,
  tol = 1e-06,
  Dmat = NULL,
  Dmat_type = c("time-avg", "typical-visit", "weighted-avg", "weighted-sq"),
  Dmat_weights = NULL,
  Dmat_rescale = TRUE,
  ar = c("none", "ar1"),
  ar_rho = NA_real_,
  slope = c("none", "subject", "method", "custom"),
  slope_var = NULL,
  slope_Z = NULL,
  drop_zero_cols = TRUE,
  vc_select = c("auto", "none"),
  vc_alpha = 0.05,
  vc_test_order = c("subj_time", "subj_method"),
  include_subj_method = NULL,
  include_subj_time = NULL,
  sb_zero_tol = 1e-10
)

\method{print}{icc_rm_reml}(
  x,
  digits = 4,
  ci_digits = 4,
  n = NULL,
  topn = NULL,
  max_vars = NULL,
  width = NULL,
  show_ci = NULL,
  ...
)

\method{summary}{icc_rm_reml}(
  object,
  digits = 4,
  ci_digits = 2,
  n = NULL,
  topn = NULL,
  max_vars = NULL,
  width = NULL,
  show_ci = NULL,
  ...
)

\method{print}{summary.icc_rm_reml}(
  x,
  digits = NULL,
  n = NULL,
  topn = NULL,
  max_vars = NULL,
  width = NULL,
  show_ci = NULL,
  ...
)
}
\arguments{
\item{data}{A data frame.}

\item{response}{Character. Response variable name.}

\item{subject}{Character. Subject ID variable name.}

\item{method}{Character or \code{NULL}. Optional column name of method factor
(added to fixed effects).}

\item{time}{Character or \code{NULL}. Optional column name of time factor
(added to fixed effects).}

\item{type}{Character scalar; one of \code{c("consistency","agreement")}.
For \code{"consistency"}, systematic fixed method differences are not
penalized through \eqn{S_B}. For \code{"agreement"}, the fixed-effect
dispersion term \eqn{S_B} is added to the denominator.}

\item{ci}{Logical. If \code{TRUE}, return a CI container for the repeated ICC.}

\item{conf_level}{Numeric in \eqn{(0,1)}. Confidence level when
\code{ci = TRUE} (default \code{0.95}).}

\item{n_threads}{Integer \eqn{\geq 1}. Number of OpenMP threads to use for
computation. Defaults to \code{getOption("matrixCorr.threads", 1L)}.}

\item{ci_mode}{Character scalar; one of \code{c("auto","raw","logit")}.
Controls how confidence intervals are computed when \code{ci = TRUE}.
If \code{"raw"}, a Wald CI is formed on the ICC scale and truncated to
\code{[0,1]}. If \code{"logit"}, a Wald CI is computed on the
\eqn{\mathrm{logit}(\mathrm{ICC})} scale and back-transformed to the
original scale. If \code{"auto"} (default), the backend chooses per estimate
between the raw-scale and logit-scale interval.}

\item{verbose}{Logical. If \code{TRUE}, prints a structured summary of the
fitted variance components and \eqn{S_B} for each fit. Default \code{FALSE}.}

\item{digits}{Integer \eqn{(\ge 0)}. Number of decimal places to use in the
printed summary when \code{verbose = TRUE}. Default \code{4}.}

\item{use_message}{Logical. When \code{verbose = TRUE}, verbose summaries
are emitted with \pkg{cli} messages.}

\item{interaction}{Logical. Include \code{method:time} interaction?
(default \code{FALSE}).}

\item{max_iter}{Integer. Maximum iterations for variance-component updates
(default \code{100}).}

\item{tol}{Numeric. Convergence tolerance on parameter change
(default \code{1e-6}).}

\item{Dmat}{Optional \eqn{n_t \times n_t} numeric matrix to weight/aggregate
time-specific fixed biases in the \eqn{S_B} quadratic form. If supplied, it
is used (after optional mass rescaling; see \code{Dmat_rescale}) whenever at
least two \emph{present} time levels exist; otherwise it is ignored. \strong{If
\code{Dmat} is \code{NULL}}, a canonical kernel \eqn{D_m} is \emph{constructed}
from \code{Dmat_type} and \code{Dmat_weights} (see below). \code{Dmat} should be
symmetric positive semidefinite; small asymmetries are symmetrized internally.}

\item{Dmat_type}{Character, one of \code{c("time-avg","typical-visit",
  "weighted-avg","weighted-sq")}. Only used when \code{Dmat = NULL}.
It selects the aggregation target for time-specific fixed biases in
\eqn{S_B}. Options are:

\itemize{
\item \code{"time-avg"}: square of the time-averaged bias, \eqn{D_m=(1/n_t)\,11^\top}.
\item \code{"typical-visit"}: average of squared per-time biases, \eqn{D_m=I_{n_t}}.
\item \code{"weighted-avg"}: square of a weighted average, \eqn{D_m=n_t\,w\,w^\top} with \eqn{\sum w=1}.
\item \code{"weighted-sq"}: weighted average of squared biases, \eqn{D_m=n_t\,\mathrm{diag}(w)} with \eqn{\sum w=1}.
}
Pick \code{"time-avg"} for ICC targeting the time-averaged measurement; pick
\code{"typical-visit"} for ICC targeting a randomly sampled visit (typical
occasion). Default \code{"time-avg"}.}

\item{Dmat_weights}{Optional numeric weights \eqn{w} used when
\code{Dmat_type \%in\% c("weighted-avg","weighted-sq")}. Must be nonnegative and
finite. If \code{names(w)} are provided, they should match the \emph{full} time
levels in \code{data}; they are aligned to the \emph{present} time subset per fit.
If unnamed, the length must equal the number of present time levels. In all cases
\eqn{w} is internally normalized to sum to 1.}

\item{Dmat_rescale}{Logical. When \code{TRUE} (default), the supplied/built
\eqn{D_m} is rescaled to satisfy the simple mass rule
\eqn{1^\top D_m 1 = n_t}. This keeps the \eqn{S_B} denominator invariant and
harmonizes with the time-averaging factors used for the variance terms.}

\item{ar}{Character. Residual correlation structure: \code{"none"} (iid) or
\code{"ar1"} for subject-level AR(1) correlation within contiguous time
runs. Default \code{c("none")}.}

\item{ar_rho}{Numeric in \eqn{(-0.999,\,0.999)} or \code{NA}.
If \code{ar = "ar1"} and \code{ar_rho} is finite, it is treated as fixed.
If \code{ar = "ar1"} and \code{ar_rho = NA}, \eqn{\rho} is estimated by
profiling a 1-D objective (REML when available; an approximation otherwise).
Default \code{NA_real_}.}

\item{slope}{Character. Optional extra random-effect design \eqn{Z}.
With \code{"subject"} a single random slope is added (one column in \eqn{Z});
with \code{"method"} one column per method level is added; with
\code{"custom"} you provide \code{slope_Z} directly. Default
\code{c("none","subject","method","custom")}.}

\item{slope_var}{For \code{slope \%in\% c("subject","method")}, a character
string giving the name of a column in \code{data} used as the slope regressor
(e.g., centered time). It is looked up inside \code{data}; do not
pass the vector itself. NAs are treated as zeros in \eqn{Z}.}

\item{slope_Z}{For \code{slope = "custom"}, a numeric matrix with \eqn{n}
rows (same order as \code{data}) providing the full extra random-effect
design \eqn{Z}. \strong{Each column of \code{slope_Z} has its own variance
component} \eqn{\sigma_{Z,j}^2}; columns are treated as \emph{uncorrelated}
(diagonal block in \eqn{G}). Ignored otherwise.}

\item{drop_zero_cols}{Logical. When \code{slope = "method"}, drop all-zero
columns of \eqn{Z} after subsetting (useful in pairwise fits). Default
\code{TRUE}.}

\item{vc_select}{Character scalar; one of \code{c("auto","none")}.
Controls how the subject by method \eqn{\sigma^2_{A\times M}} ("subj_method") and
subject by time \eqn{\sigma^2_{A\times T}} ("subj_time") variance components are
included. If \code{"auto"} (default), the function performs boundary-aware
REML likelihood-ratio tests (LRTs; null on the boundary at zero with a
half-\eqn{\chi^2_1} reference) to decide whether to retain each component,
in the order given by \code{vc_test_order}. If \code{"none"}, no testing
is done and inclusion is taken from \code{include_subj_method}/\code{include_subj_time}
(or, if \code{NULL}, from the mere presence of the corresponding factor in
the design). In pairwise fits, the decision is made independently for each
method pair.}

\item{vc_alpha}{Numeric scalar in \eqn{(0,1)}; default \code{0.05}.
Per-component significance level for the boundary-aware REML LRTs used when
\code{vc_select = "auto"}. The tests are one-sided for variance components
on the boundary and are not multiplicity-adjusted.}

\item{vc_test_order}{Character vector (length 2) with a permutation of
\code{c("subj_time","subj_method")}; default \code{c("subj_time","subj_method")}. Specifies the order
in which the two variance components are tested when \code{vc_select = "auto"}.
The component tested first may be dropped before testing the second. If a
factor is absent in the design (e.g., no time factor so "subj_time" is undefined),
the corresponding test is skipped.}

\item{include_subj_method, include_subj_time}{Logical scalars or \code{NULL}.
When \code{vc_select = "none"}, these control whether the
\eqn{\sigma^2_{A\times M}} ("subj_method") and \eqn{\sigma^2_{A\times T}} ("subj_time")
random effects are included (\code{TRUE}) or excluded (\code{FALSE}) in the model.
If \code{NULL} (default), inclusion defaults to the presence of the
corresponding factor in the data (i.e., at least two method/time levels).
When \code{vc_select = "auto"}, these arguments are ignored (automatic
selection is used instead).}

\item{sb_zero_tol}{Non-negative numeric scalar; default \code{1e-10}.
Numerical threshold for the fixed-effect dispersion term \eqn{S_B}.
After computing \eqn{\widehat{S_B}} and its delta-method variance, if
\eqn{\widehat{S_B} \le} \code{sb_zero_tol} or non-finite, the procedure
treats \eqn{S_B} as fixed at zero in the delta step.}

\item{x}{For \code{print()}, an object returned by \code{icc_rm_reml()} or
\code{summary.icc_rm_reml()}.}

\item{ci_digits}{Integer; number of digits for confidence interval bounds in
printed method summaries.}

\item{n}{Optional row threshold for compact preview output.}

\item{topn}{Optional number of leading/trailing rows to show when truncated.}

\item{max_vars}{Optional maximum number of visible columns; \code{NULL} derives
this from console width.}

\item{width}{Optional display width; defaults to \code{getOption("width")}.}

\item{show_ci}{One of \code{"yes"} or \code{"no"}.}

\item{...}{Passed to the underlying display helpers.}

\item{object}{For \code{summary()}, an object returned by \code{icc_rm_reml()}.}
}
\value{
A repeated-measures pairwise ICC object. Without confidence intervals the
result is a symmetric matrix of class \code{c("icc_rm_reml", "icc", "matrix")}.
With confidence intervals it is a list with \code{est}, \code{lwr.ci}, and \code{upr.ci}
and class \code{c("icc_rm_reml", "icc_ci", "icc")}. Both carry the fitted
variance-component matrices as attributes.
}
\description{
Computes pairwise repeated-measures intraclass correlation coefficients from
long-format data using the same REML and Woodbury-identity backend used by
the repeated-measures agreement models.
}
\details{
The repeated-measures model is fit separately for each method pair using the
same REML and Woodbury-identity backend used by the repeated-measures
concordance estimator.

\strong{Kernel \eqn{D_m} and the fixed-bias term \eqn{S_B}.}
Let \eqn{d = L^\top \hat\beta} stack the within-time, pairwise method
differences, grouped by time. The symmetric positive semidefinite kernel
\eqn{D_m \succeq 0} selects which functional of the bias profile is targeted
by \eqn{S_B}. Internally, the code rescales any supplied or constructed
\eqn{D_m} to satisfy \eqn{1^\top D_m 1 = n_t} for stability and comparability.

\itemize{
\item \code{Dmat_type = "time-avg"} targets the square of the
time-averaged bias.
\item \code{Dmat_type = "typical-visit"} targets the average of squared
per-time biases.
\item \code{Dmat_type = "weighted-avg"} targets the square of a weighted
time average.
\item \code{Dmat_type = "weighted-sq"} targets the weighted average of
squared per-time biases.
}

As in the repeated-measures concordance implementation, \eqn{S_B} is the
fitted fixed-effect dispersion term induced by \eqn{D_m}. It enters the
denominator only for \code{type = "agreement"}.

\strong{Time-averaging and shrinkage factors.}
The fitted variance components reported in the summary are
\eqn{\sigma_S^2}, \eqn{\sigma_{S\times M}^2}, \eqn{\sigma_{S\times T}^2},
and \eqn{\sigma_E^2}, stored respectively as \code{sigma2_subject},
\code{sigma2_subject_method}, \code{sigma2_subject_time}, and \code{sigma2_error}.

The repeated-measures ICC always uses \eqn{\sigma_S^2} in the numerator only.
The denominator uses the same time-averaging logic already used by the
repeated-measures concordance backend, through two pair-specific factors
\eqn{\bar{\kappa}_g} and \eqn{\bar{\kappa}_e}.

If \code{time} is absent, the implementation sets
\deqn{ \bar{\kappa}_g = 0, \qquad \bar{\kappa}_e = 1. }

If \code{time} is present and the target is a single visit
(\code{Dmat_type \%in\% c("typical-visit", "weighted-sq")}), the implementation
leaves the time-varying terms unshrunk:
\deqn{ \bar{\kappa}_g = 1, \qquad \bar{\kappa}_e = 1. }

If \code{time} is present and the target is time-averaged
(\code{Dmat_type \%in\% c("time-avg", "weighted-avg")}), then for each observed
subject-method unit with \eqn{T} distinct observed visits:
\itemize{
\item with equal weights,
\deqn{ \kappa_g = \frac{1}{T}, \qquad
         \kappa_e = \frac{T + 2\sum_{h=1}^{T-1}(T-h)\rho^h}{T^2}, }
with \eqn{\kappa_e=\kappa_g} when residuals are iid;
\item with normalized visit weights \eqn{w_1,\ldots,w_T},
\deqn{ \kappa_g = \sum_{t=1}^{T} w_t^2, \qquad
         \kappa_e = \sum_{t=1}^{T}\sum_{s=1}^{T} w_t w_s \rho^{|t-s|}, }
with \eqn{\kappa_e=\kappa_g} when residuals are iid.
}

With unbalanced \eqn{T}, the implementation averages the per-unit
\eqn{\kappa} values across the observations contributing to the pair and then
clamps both \eqn{\bar{\kappa}_g} and \eqn{\bar{\kappa}_e} to
\eqn{[10^{-12},\,1]} for numerical stability.

\strong{Repeated-measures ICC.}
Let \eqn{\sigma_{S\times M,\mathrm{eff}}^2} denote the effective
subject-by-method variance term, equal to \eqn{\sigma_{S\times M}^2} when
the subject-by-method random effect is included and \eqn{0} otherwise. Let
\eqn{\sigma_{S\times T,\mathrm{eff}}^2} denote the effective subject-by-time
variance term, equal to \eqn{\sigma_{S\times T}^2} when the subject-by-time
random effect is included and \eqn{0} otherwise.

For \code{type = "consistency"}, the reported ICC is
\deqn{ \mathrm{ICC}_{\mathrm{consistency}} \;=\;
      \frac{\sigma_S^2}{
      \sigma_S^2 + \sigma_{S\times M,\mathrm{eff}}^2 +
      \bar{\kappa}_g\,\sigma_{S\times T,\mathrm{eff}}^2 +
      \bar{\kappa}_e\,\sigma_E^2}. }

For \code{type = "agreement"}, the denominator additionally includes \eqn{S_B}:
\deqn{ \mathrm{ICC}_{\mathrm{agreement}} \;=\;
      \frac{\sigma_S^2}{
      \sigma_S^2 + \sigma_{S\times M,\mathrm{eff}}^2 +
      \bar{\kappa}_g\,\sigma_{S\times T,\mathrm{eff}}^2 +
      \bar{\kappa}_e\,\sigma_E^2 + S_B}. }

This differs from repeated-measures concordance because ICC uses only
\eqn{\sigma_S^2} in the numerator, whereas the concordance numerator also
includes the time-averaged subject-time term. Extra random-effect variances
\eqn{\{\sigma_{Z,j}^2\}} from \code{slope} / \code{slope_Z} are estimated by the shared
backend but are not included in the ICC denominator.

\strong{CIs / SEs (delta method for ICC).}
Let \eqn{I_A = 1} for \code{type = "agreement"} and \eqn{I_A = 0} for
\code{type = "consistency"}, and define
\deqn{ \theta \;=\; \big(\sigma_S^2,\ \sigma_{S\times M,\mathrm{eff}}^2,\
\sigma_{S\times T,\mathrm{eff}}^2,\ \sigma_E^2,\ S_B\big)^\top. }
Write \eqn{\mathrm{ICC}(\theta)=N/D} with
\deqn{ N = \sigma_S^2, \qquad
       D = \sigma_S^2 + \sigma_{S\times M,\mathrm{eff}}^2 +
           \bar{\kappa}_g\,\sigma_{S\times T,\mathrm{eff}}^2 +
           \bar{\kappa}_e\,\sigma_E^2 + I_A S_B. }
The gradient used in the delta method is
\deqn{ \frac{\partial\,\mathrm{ICC}}{\partial \sigma_S^2}
      \;=\; \frac{
      \sigma_{S\times M,\mathrm{eff}}^2 +
      \bar{\kappa}_g\,\sigma_{S\times T,\mathrm{eff}}^2 +
      \bar{\kappa}_e\,\sigma_E^2 + I_A S_B}{D^2}, }
\deqn{ \frac{\partial\,\mathrm{ICC}}{\partial \sigma_{S\times M,\mathrm{eff}}^2}
      \;=\; -\,\frac{N}{D^2}, \qquad
       \frac{\partial\,\mathrm{ICC}}{\partial \sigma_{S\times T,\mathrm{eff}}^2}
      \;=\; -\,\frac{\bar{\kappa}_g\,N}{D^2}, }
\deqn{ \frac{\partial\,\mathrm{ICC}}{\partial \sigma_E^2}
      \;=\; -\,\frac{\bar{\kappa}_e\,N}{D^2}, \qquad
       \frac{\partial\,\mathrm{ICC}}{\partial S_B}
      \;=\; -\,\frac{I_A\,N}{D^2}. }

The covariance matrix \eqn{\widehat{\mathrm{Var}}(\hat\theta)} is assembled
from the same REML fit:
\itemize{
\item the
\eqn{(\sigma_S^2,\sigma_{S\times M,\mathrm{eff}}^2,
  \sigma_{S\times T,\mathrm{eff}}^2)} block comes from the empirical
subject-level covariance of the per-subject REML component updates;
\item \eqn{\widehat{\mathrm{Var}}(\hat\sigma_E^2)} is approximated as the
variance of the weighted mean of subject-level residual quadratic forms;
\item \eqn{\widehat{\mathrm{Var}}(S_B)} uses the fixed-effect quadratic-form
delta method already computed in the backend.
}
Cross-covariances across these blocks are ignored as a large-sample
simplification, so
\deqn{ \widehat{\mathrm{se}}\{\widehat{\mathrm{ICC}}\}
      \;=\; \sqrt{\,\nabla \mathrm{ICC}(\hat\theta)^\top\,
                    \widehat{\mathrm{Var}}(\hat\theta)\,
                    \nabla \mathrm{ICC}(\hat\theta)\,}. }

If \code{ci_mode = "raw"}, a Wald interval is formed on the ICC scale,
\deqn{ \widehat{\mathrm{ICC}} \;\pm\; z_{1-\alpha/2}\,
      \widehat{\mathrm{se}}\{\widehat{\mathrm{ICC}}\}, }
and truncated to \eqn{[0,1]}. If \code{ci_mode = "logit"}, the backend applies
the same Wald construction after the transform
\eqn{\phi = \mathrm{logit}(\mathrm{ICC})}, with
\deqn{ \widehat{\mathrm{se}}(\hat\phi)
      \;\approx\; \frac{\widehat{\mathrm{se}}\{\widehat{\mathrm{ICC}}\}}
      {\widehat{\mathrm{ICC}}\,(1-\widehat{\mathrm{ICC}})}, }
and then back-transforms
\deqn{ \mathrm{logit}^{-1}\!\Big(
      \hat\phi \pm z_{1-\alpha/2}\,\widehat{\mathrm{se}}(\hat\phi)\Big). }
If \code{ci_mode = "auto"}, the backend selects between the raw-scale and
logit-scale interval per estimate, typically preferring the logit form near
the boundaries.

\strong{Choosing \eqn{\rho} for AR(1).}
When \code{ar="ar1"} and \code{ar_rho = NA}, \eqn{\rho} is estimated by
profiling the REML log-likelihood at \eqn{(\hat\beta,\hat G,\hat\sigma_E^2)}.
With very few visits per subject, \eqn{\rho} can be weakly identified; consider
sensitivity checks over a plausible range.
}
\section{Notes on stability and performance}{

All per-subject solves are \eqn{r\times r} with
\eqn{r = 1 + n_m + n_t + q_Z}, so cost scales with the number of subjects and
the fixed-effects dimension rather than the total number of observations.
Solvers use symmetric positive-definite paths with a small diagonal ridge and
pseudo-inverse fallback, which helps for very small or unbalanced subsets and
near-boundary estimates. For \code{AR(1)}, observations are ordered by time
within subject; \code{NA} time codes break the run, and gaps between factor
levels are treated as regular steps.

Heteroscedastic slopes across \eqn{Z} columns are supported. Each \eqn{Z}
column has its own variance component \eqn{\sigma_{Z,j}^2}, but
cross-covariances among \eqn{Z} columns are set to zero.
}

\section{Threading and BLAS guards}{

The C++ backend uses OpenMP loops while also forcing vendor BLAS libraries to
run single-threaded so that overall CPU usage stays predictable. This guard
is applied to OpenBLAS, Apple's Accelerate, and Intel MKL when their runtime
controls are available. You can opt out manually by setting
\code{MATRIXCORR_DISABLE_BLAS_GUARD=1} in the environment before loading the
package.
}

\examples{
set.seed(321)
n_id <- 20
n_time <- 3
id <- factor(rep(seq_len(n_id), each = 2 * n_time))
method <- factor(rep(rep(c("A", "B"), each = n_time), times = n_id))
time <- factor(rep(seq_len(n_time), times = 2 * n_id))

subj <- rnorm(n_id, sd = 1)[as.integer(id)]
subj_method <- rnorm(n_id * 2, sd = 0.25)
sm <- subj_method[(as.integer(id) - 1L) * 2L + as.integer(method)]
y <- subj + sm + 0.3 * (method == "B") + rnorm(length(id), sd = 0.35)

dat_rm <- data.frame(y = y, id = id, method = method, time = time)

fit_icc_rm <- icc_rm_reml(
  dat_rm,
  response = "y",
  subject = "id",
  method = "method",
  time = "time",
  type = "consistency",
  ci = TRUE
)
print(fit_icc_rm)
summary(fit_icc_rm)
confint(fit_icc_rm)
tidy(fit_icc_rm)

}
\references{
Shrout PE, Fleiss JL (1979). Intraclass correlations: uses in assessing
rater reliability. Psychological Bulletin, 86(2), 420-428.

McGraw KO, Wong SP (1996). Forming inferences about some intraclass
correlation coefficients. Psychological Methods, 1(1), 30-46.
}
\seealso{
\code{icc()}, \code{\link[=ccc]{ccc()}}, \code{\link[=ccc_rm_reml]{ccc_rm_reml()}}, \code{\link[=ba]{ba()}}, \code{\link[=ba_rm]{ba_rm()}}, \code{\link[=rmcorr]{rmcorr()}}
}
