For a consolidated capability matrix, a fully synthetic teaching
example, and help with common messages, see
vignette("support-and-troubleshooting").
Why use REPAIR?
Random-Effect Prediction Adjustment for Inference in Regression (REPAIR) addresses questions about relationships involving unit-specific processes. For example, researchers may ask whether a person’s rate of improvement predicts a later outcome, or whether their responses in two tasks are related. Mixed models estimate these processes using random intercepts and slopes, but their predictions contain sampling error and may be shrunken toward the population mean. Using those predictions as ordinary observed variables in a second regression can distort coefficients and uncertainty.
REPAIR obtains likelihood-only predictions that remove shrinkage, retains their unit-specific sampling-error covariances, and accounts for that error in the second-stage regression. Removing shrinkage alone does not remove sampling error. This approach is useful for studying relationships among underlying processes while retaining separately fitted MLMs.
What is being estimated?
REPAIR estimates a linear structural regression involving latent random coefficients from a MLM. A likelihood-only prediction has an additive sampling-error representation. REPAIR uses the prediction and its sampling-error covariance in a modified method-of-moments (M-MOM) regression. A BLUP’s posterior covariance is not the sampling-error covariance required by this estimator.
The high-level interface supports Gaussian lmer() or
linear lme() measurement models, each with one target
grouping factor. lmer models may include nuisance groups contained
within targets; see vignette("nested-nuisance"). Multiple
referenced models require an explicit cross-model prediction-error
policy; see vignette("multiple-models"). The structural
model is additive and includes an intercept. Predictions are deviations
from the fitted fixed effects. The MLM remains fixed while structural
relationships are explored. Alternatively, repair_mlm()
specifications are fitted by their native engines during the consuming
call.
1. Fit and check the MLM
growth <- lme4::lmer(Reaction ~ Days + (Days | Subject), lme4::sleepstudy)
models <- list(growth = growth)
repair_effects(models)
#> model group term n_levels
#> 1 growth Subject (Intercept) 18
#> 2 growth Subject Days 18Independent random-effect blocks for the same grouping factor (such
as (Days || Subject)) are also supported; they are aligned
by level and scalar coefficient before prediction extraction.
Inspect convergence and the substantive adequacy of this model with
the normal lme4 tools. REPAIR retains optimizer messages
and singularity status in the structural summary. A singular
random-effect covariance does not by itself prevent GLS prediction
extraction; a rank-deficient within-unit design does.
repair_effects() gives scalar coefficient names. For
example, a factor random slope may expand into several coefficients:
select each by its actual name. "(Intercept)" is canonical;
"1" and "Intercept" are accepted aliases.
Model names resolve ambiguous coefficient names across fits. The
optional group argument resolves coefficient names shared
by several groups within a model; select one target group per model. For
an unambiguous coefficient, re(Days) and
re("Days") are equivalent and model can be
omitted, including with one named or unnamed MLM. A single MLM can still
have the same coefficient name in several grouping factors; supply
group in that case. The error message identifies matching
model/group/term combinations instead of assuming that
model is always needed.
Bare names are literal syntax: re(Days) does not
evaluate a Days variable in the data or formula
environment. Calls such as re(get("Days")) and
re(Days + 1) remain unsupported. Keep model and group names
quoted, for example
re(Days, model = "growth", group = "Subject"). Use a quoted
coefficient name or backticks for nonsyntactic names. If choosing
coefficient names in a program, insert the actual string when
constructing the formula, rather than expecting
re(variable) to look up the value of variable.
One equation can combine predictions from separate fits when you
explicitly specify their cross-model prediction-error covariance policy;
see vignette("multiple-models") for the independence and
supplied-covariance options.
2. Supply the analysis scope
people <- data.frame(
person = levels(lme4::sleepstudy$Subject),
observed = seq_len(18),
category = factor(rep(c("A", "B", "C"), 6))
)These structural variables are invented for demonstration. The
id argument names the ID column in this table, which may
differ from the MLM grouping name (Subject). Values must
identify the same units. IDs are matched as character values; preserve
distinctions such as "001" versus "1".
Each row requests one analysis person. Duplicate, missing, or empty
IDs always fail. Repeated-observation data must first be reduced to a
deliberate unit-level table; REPAIR does not choose an aggregation rule.
Extra MLM IDs outside the requested scope are recorded as
unused_prediction_ids.
Optional integrated MLM fitting
repair_mlm() describes the first-stage
MLM, while the formula in repair() describes the
structural model. Constructing a specification does not
fit it. The MLM’s repeated observations and the structural table remain
explicit:
inline <- repair(
re(Days) ~ observed,
models = repair_mlm(Reaction ~ Days + (Days | Subject), lme4::sleepstudy),
data = people, id = "person"
)
repair_coefficients(inline)
#> term estimate std.error statistic p.value conf.low conf.high
#> 1 (Intercept) -2.9721078 3.2147349 -0.9245266 0.3552122 -9.272872 3.3286569
#> 2 observed 0.3128535 0.2969909 1.0534109 0.2921527 -0.269238 0.8949449
#> conf.level
#> 1 0.95
#> 2 0.95You can mix fitted models and specifications in a named list. Each
call to repair(), repair_data(), or
repair_effects() fits each supplied specification once. For
repeated structural analyses or discovery, reuse
inline@mlm_fit. The structural backend still
chooses R/Rcpp computation; engine selects the native MLM
fitter. Neither choice changes the supported covariance assumptions.
Native arguments must be fully named. For lmer, weights,
offset and subset retain native
data-expression semantics, such as weights = precision when
precision is a repeated-data column. Other arguments,
including control and contrast objects, are evaluated when the
specification is created. Native warnings remain visible; fitting errors
identify the model name and engine.
The helper retains data for ordinary fitted-model inspection.
Refitting and bootstrapping still require explicit original repeated and
structural data and the usual identity checks. Supported data-only
recipes replay natively; external vectors, custom transformations and
unsupported expressions can still require an explicit
refitter. Initial subset/omission is handled by the native
fitter; replacement fits retain the existing strict effective-row
requirements.
3. Inspect matched predictions and covariances
structural <- re("Days", model = "growth") ~ observed
analysis <- repair_data(structural, models, people, id = "person")
analysis
#> REPAIR analysis data: 18 people, 1 predictor columns
#> Excluded: 0 of 18 requested IDs
#> model group term label role
#> growth Subject Days re("Days", model = "growth") outcome
head(analysis@ids)
#> [1] "308" "309" "310" "330" "331" "332"
head(analysis@outcome)
#> 308 309 310 330 331 332
#> 11.2974165 -8.2055005 -4.3523872 -7.4592132 -5.2012672 -0.9005181
head(analysis@predictors)
#> observed
#> 308 1
#> 309 2
#> 310 3
#> 330 4
#> 331 5
#> 332 6
head(analysis@err_y)
#> 308 309 310 330 331 332
#> 7.938667 7.938667 7.938667 7.938667 7.938667 7.938667
analysis@diagnostics$excluded
#> [1] id reason
#> <0 rows> (or 0-length row.names)For ordinary inspection, use
repair_predictions(analysis) and
repair_prediction_covariance(analysis). After fitting,
repair_coefficients(fit) and
repair_diagnostics(fit, table = "excluded") provide
reporting tables. See vignette("extracting-results") for
stable schemas, ordering, and joins.
The data frame’s order is retained. For advanced matrix-level inspection, the internal covariance contract is:
| Property | Meaning and dimensions |
|---|---|
ids |
Analysis IDs, length n |
outcome |
Outcome predictions or observed values, length n |
predictors |
Predictor matrix, n by q, excluding the intercept |
err_x |
Predictor-error covariance, q by q by n |
err_y |
Outcome-error variance, length n |
err_xy |
Outcome/predictor-error covariance, n by q |
effects |
Model, grouping factor, coefficient, and structural role |
predictions |
Full prediction-extraction result and per-cluster diagnostics |
diagnostics |
Cohort counts, exclusions, unused IDs, and model messages |
All observed variables, including factor contrast columns, have zero measurement error. Covariances are indexed and subset together with predictions. No zero cross-covariance assumption is made for two coefficients from the same model.
4. Fit and interpret
fit <- repair(structural, models, people, id = "person")
summary(fit)
#> REPAIR structural regression
#> re("Days", model = "growth") ~ observed
#> Units: 18 analyzed / 18 requested; 0 excluded
#> MLM: growth (lme4; group Subject; 0 IDs outside scope)
#> Cross-model prediction errors: not applicable (one model)
#> Predictions: likelihood-only random deviations
#> model group term role
#> growth Subject Days outcome
#>
#> Posterior reliability (structural scope; equal unit weights):
#> model term role measure reliability n_units n_defined
#> growth Days outcome marginal 0.849 18 18
#> growth Days outcome residualized 0.828 18 18
#>
#> estimate se zstat pval ci_low ci_high
#> (Intercept) -2.9721 3.215 -0.9245 0.3552 -9.2729 3.3287
#> observed 0.3129 0.297 1.0534 0.2922 -0.2692 0.8949
#>
#> Regularization (preliminary / final): minimum / minimum
#> Error-moment subtraction multipliers: 0.8333 / 0.8333
#> Largest analysis-weight fraction: 0.0556 ; weight-equivalent count: 18
#> Moment conditioning and unit weights: repair_diagnostics(fit).
#> Conditional on fitted MLM parameters; model-based normal SEs and intervals.
coef(fit)
#> (Intercept) observed
#> -2.9721078 0.3128535
vcov(fit)
#> (Intercept) observed
#> (Intercept) 10.3345206 -0.83793411
#> observed -0.8379341 0.08820359
confint(fit, parm = "observed", level = 0.90)
#> 5 % 95 %
#> observed -0.1756531 0.80136
nobs(fit)
#> [1] 18nobs() counts people. summary() returns an
inspectable list and prints effect sources, sample counts, coefficient
estimates, standard errors, normal z tests, 95% intervals, and
regularization settings. fit@analysis_data contains the
same assembly information described above. Numerical M-MOM failures
issue a warning and return @struc_fit@converged = FALSE;
the summary prints the reason, and coef(),
vcov(), and confint() refuse to return failed
estimates.
Inference conditions on fitted MLM parameters, including variance components and fixed coefficients. The covariance calculation uses the modified final predictor moment for both sides of its sandwich expression, preliminary slopes in the extra error-covariance term, and squared inverse case-variance weights in that term. It assumes the model-based normal-error covariance and independent analysis people. It is not a robust sandwich estimator and does not include uncertainty from estimating the MLM.
Random effects on either side
An observed outcome can be regressed on a random effect:
predictor_fit <- repair(
observed ~ re("Days", model = "growth") + category,
models, people, id = "person"
)
coef(predictor_fit)
#> (Intercept) re("Days", model = "growth")
#> 7.7612794 0.3030291
#> categoryB categoryC
#> 2.0808325 3.1353293Both sides may contain random effects from the same MLM:
both <- repair(
re("Days", model = "growth") ~ re("(Intercept)", model = "growth") + observed,
models, people, id = "person"
)
both@analysis_data@err_xy[1:3, , drop = FALSE]
#> re("(Intercept)", model = "growth") observed
#> 308 -35.724 0
#> 309 -35.724 0
#> 310 -35.724 0The nonzero outcome/predictor-error covariance is retained. Adding a
constant fixed coefficient changes the intercept interpretation; it does
not turn a random deviation into a general unit-specific effect when
fixed interactions or person-varying covariates contribute. The
structural workflow consistently uses deviations. The low-level
prediction extractor’s include_fixed option adds only
matching fixed coefficients and errors if any coefficient lacks a
match.
Missingness is a decision
incomplete <- people
incomplete$observed[2] <- NA_real_
incomplete$person[1] <- "not-in-MLM"
# Default na_action = "fail" would stop and identify these rows.
kept <- repair_data(structural, models, incomplete, id = "person", na_action = "omit")
#> Warning: Omitting 2 analysis row(s); inspect `@diagnostics$excluded`.
kept@diagnostics$excluded
#> id reason
#> 1 not-in-MLM ID absent from MLM growth
#> 2 309 missing/nonfinite observed variable observedThe omission option covers unmatched IDs, missing/nonfinite observed
variables, and failed prediction extraction blocks. It warns and records
all reasons per excluded ID. It never permits duplicate/missing IDs. At
least max(8, q + 2) complete people are required, where q
counts predictor columns after factor expansion. A rank-deficient
structural design fails with a message before fitting M-MOM.
Regularization and lower-level use
regularization = "minimum" uses q + 2 as the
regularization constant at both moment steps. "none" sets
the error-moment subtraction multiplier to one: it disables
stabilization but still corrects measurement error.
"custom" requires alpha >= q + 2. The
summary reports the resulting subtraction multipliers; these need not
equal the input regularization constant. "step_up" selects
preliminary and final alphas sequentially and records every candidate
and any fallback to minimum alpha; see vignette("step-up").
Refits and bootstrap samples repeat the selection rather than freezing
selected alphas.
To choose different controls at the two moment steps, or to supply
validated sampling-error inputs from another source, use
fit_mmom():
manual <- fit_mmom(list(
outcome = analysis@outcome,
predictors = analysis@predictors,
err_x = analysis@err_x,
err_y = analysis@err_y,
err_xy = analysis@err_xy
), backend = "r")
stopifnot(isTRUE(all.equal(unname(coef(fit)), manual@coefficients$estimate)))The lower-level prediction extractor repair_ranef_gls()
returns group-keyed S7 properties @predictions,
@prediction_error_covariance, @levels,
@terms, and @diagnostics. Single-group
nlme extraction supports the residual structures documented
in vignette("nlme-workflow"). lmer nuisance effects
entirely contained within each target person are supported; see
vignette("nested-nuisance"). Shared nuisance random effects
remain rejected: their cross-person prediction errors cannot enter the
row-wise M-MOM contract. Multilevel nlme fits remain unsupported.
Refit an explicitly revised analysis
repair_refit() verifies the original calculation before
rebuilding one supported MLM on replacement data. It retains structural
controls and reports a replay audit; see
vignette("refitting") for inputs, coding and deterministic
draw restrictions. For experimental person-level sampling and percentile
intervals, use repair_bootstrap() separately; see
vignette("person-bootstrap").
Deliberate boundaries
The formula grammar accepts an observed variable or re()
as outcome, and an additive sum of observed variables and
re() references as predictors. 1 + is
optional. Interactions, nonlinear prediction transformations, offsets,
., omitted intercepts, intercept-only models, and multiple
equations are rejected. You may precompute transformations of
observed variables in data and refer to their
column names. Character predictors must be explicitly converted to
factors.
Automatic MLM fitting, cross-model covariance estimation, additional structural grammars are future work, not silent fallback behavior. See the source repository’s design plan and audit for extension requirements and reproducibility tests.
Reliability and diagnostic tables
Use repair_reliability(fit) for the manuscript’s
marginal and, where applicable, intercept-residualized posterior
reliability. repair_diagnostics(fit) collects sample
accounting, prediction extraction failures, input error variances,
regularization, corrected-moment conditioning, and weight concentration
in tables. The summary now includes compact reliability and weight
information. See vignette("reliability-diagnostics") for
scope definitions, undefined values, plots, and the distinction between
posterior uncertainty and prediction error.
