
Validated nlme prediction extraction and end-to-end REPAIR reproduction
Source:vignettes/nlme-workflow.Rmd
nlme-workflow.RmdFit an nlme MLM
As an alternative to fitting separately, specify the first-stage MLM
with repair_mlm(). The first formula describes fixed
effects; random describes random effects and grouping. For
example:
data(repair_example)
inline_lme <- repair(
re(day) ~ practice,
models = repair_mlm(score ~ day, repair_example$repeated,
engine = "lme", random = ~ day | person, method = "REML",
control = nlme::lmeControl(msMaxIter = 300)),
data = repair_example$people, id = "person"
)
repair_coefficients(inline_lme)
#> term estimate std.error statistic p.value conf.low conf.high
#> 1 (Intercept) -0.7895288 0.1147252 -6.881912 5.905431e-12 -1.0143861 -0.5646715
#> 2 practice 0.1754854 0.0214190 8.192979 2.548386e-16 0.1335049 0.2174659
#> conf.level
#> 1 0.95
#> 2 0.95Supported correlation and variance objects can be supplied as native
correlation and weights arguments. The same
residual-structure validation applies to specifications and fitted
inputs. keep.data = TRUE is required. See
?repair_mlm for evaluation, data retention and refitting
boundaries.
The paper uses nlme for its primary MLMs. The public
workflow for Random-Effect Prediction Adjustment for Inference in
Regression (REPAIR) accepts a fitted, single-group linear
nlme::lme() model:
growth <- nlme::lme(
Reaction ~ Days, random = ~ Days | Subject,
data = lme4::sleepstudy, keep.data = TRUE
)
people <- data.frame(Subject = levels(lme4::sleepstudy$Subject),
observed = seq_len(18)) # illustrative predictor
repair_effects(list(growth = growth))
#> model group term n_levels
#> 1 growth Subject (Intercept) 18
#> 2 growth Subject Days 18
fit <- repair(re("Days", "growth") ~ observed,
list(growth = growth), people, id = "Subject")
summary(fit)
#> REPAIR structural regression
#> re("Days", "growth") ~ observed
#> Units: 18 analyzed / 18 requested; 0 excluded
#> MLM: growth (nlme; group Subject; 0 IDs outside scope)
#> nlme singularity is not assessed; inspect the MLM fit and its fitting warnings.
#> 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.repair_effects() lists scalar random effects;
repair_data() computes and aligns their likelihood-only
predictions and error covariance by person ID; repair()
performs that assembly and fits M-MOM. These functions have the same
interface for lmer and lme inputs. Predictions remain deviations from
fixed effects, and observed structural variables are treated as
error-free.
The summary identifies the MLM backend. For nlme, singularity is not
assessed using lme4’s criterion. Inspect the MLM fit and warnings issued
when fitting it. An available nlme apVar failure message is
retained as a variance-parameter uncertainty diagnostic; its absence is
not a convergence test.
Supported covariance structures
| Component | Supported |
|---|---|
| MLM | Linear Gaussian lme, one grouping factor |
| Residual correlation | Independent, corAR1, corCAR1
|
| Residual variance | Constant, varIdent, varPower
|
| Combined structures | Supported correlation plus supported variance function |
| Retained data | Explicit data frame, keep.data = TRUE (the lme
default) |
AR(1) objects that nlme converts to
corARMA(p = 1, q = 0) for irregular integer times are
supported. This does not admit arbitrary ARMA orders. Correlation groups
must match the random-effect group; finer subgroup correlations,
multilevel lme fits, nonlinear nlme fits, and other variance/correlation
classes fail explicitly. varComb and other combinations of
variance functions have not yet been admitted. Contained lmer nuisance
groups are supported separately; see
vignette("nested-nuisance"). Shared nuisance levels remain
rejected.
The fitted covariance includes the residual scale and
variance-function weights. In particular,
varPower(~ fitted(.)) uses the weights retained by the
fitted model; recomputing them from final fitted values can differ at
convergence. The covariance is residual covariance, not posterior BLUP
covariance and not the full marginal covariance including the target
random effects.
Why observation alignment matters
An lme object’s source data, effective fitting rows, and public
response extractor need not have the same length when
subset or na.exclude is used. REPAIR uses the
effective observation IDs saved in the fitted object’s grouping
information, then aligns its retained data, fixed/random designs,
response, and covariance. It preserves fitted contrasts even if session
contrast options change. It also checks that the reconstructed designs
reproduce the saved fitted values.
Do not remove or edit the model’s retained data. If it was fitted
with keep.data = FALSE, refit with retained data. The
extractor does not re-evaluate the original data expression or subset in
the current workspace. Structural omission is still a separate decision:
na_action = "omit" refers to people in the structural scope
and retains their exclusion reasons.
Reproduce reference results from repeated observations
The package bundles three deterministic synthetic datasets. Expected results come from the paper’s production prediction extraction and M-MOM functions, cross-checked against an independent algebra implementation. No repair functions were used to generate these expectations. These are per-dataset agreement checks, not the paper’s published simulation tables or evidence of Monte Carlo coverage.
reference <- readRDS(system.file(
"extdata", "nlme-workflow-reference.rds", package = "repair"
))
reference$provenance[c("source_commit", "nlme_version",
"preliminary_moment", "variance_bread")]
#> $source_commit
#> [1] "b1f09f430d2214d5c4c8815b1386b62cb4ae159e"
#>
#> $nlme_version
#> [1] "3.1.170"
#>
#> $preliminary_moment
#> [1] "modified"
#>
#> $variance_bread
#> [1] "modified"
names(reference$cases)
#> [1] "predictor_balanced" "outcome_unbalanced" "both_ar1_ident"The balanced predictor case starts with raw repeated observations, fits the MLM, and predicts an observed distal outcome from its intercept and slope predictions:
case <- reference$cases$predictor_balanced
growth <- nlme::lme(y ~ z, random = ~ z | id, data = case$data,
control = nlme::lmeControl(msMaxIter = 300))
fit <- repair(
distal ~ re("(Intercept)", "growth") + re("z", "growth"),
models = list(growth = growth), data = case$people, id = "id"
)
actual <- tail(fit@struc_fit@coefficients, 1)[,
c("estimate", "se", "ci_low", "ci_high")]
rownames(actual) <- NULL
rbind(package = actual, production_reference = case$focal)
#> estimate se ci_low ci_high
#> package 0.9225323 0.1556743 0.6174162 1.227648
#> production_reference 0.9225323 0.1556743 0.6174162 1.227648
stopifnot(isTRUE(all.equal(actual, case$focal, tolerance = 1e-5)))For a same-model outcome/predictor-error example with heterogeneous AR(1) residuals:
case_cor <- reference$cases$both_ar1_ident
growth_cor <- nlme::lme(
y ~ z, random = ~ z | id, data = case_cor$data,
correlation = nlme::corAR1(form = ~ time | id),
weights = nlme::varIdent(form = ~ 1 | phase),
control = nlme::lmeControl(msMaxIter = 300)
)
fit_cor <- repair(re("z", "growth") ~ re("(Intercept)", "growth"),
list(growth = growth_cor), case_cor$people, id = "id")
head(fit_cor@analysis_data@err_xy) # retained cross-error covariance
#> re("(Intercept)", model = "growth")
#> p01 -0.25131401
#> p02 -0.17275815
#> p03 -0.16674623
#> p04 -0.12068647
#> p05 -0.11781640
#> p06 -0.08897551
stopifnot(isTRUE(all.equal(unname(coef(fit_cor)),
case_cor$coefficients$estimate, tolerance = 1e-5)))The test suite also refits the unbalanced outcome-error case and compares coefficients, covariance, SEs, and confidence intervals on both R and C++ backends. Separate tests construct GLS and residual covariance analytically for shuffled/missing/subset observations and the supported residual structures.
Match the reporting scale
repair() returns estimates on the supplied input scale.
The frozen production comparisons use the primary modified-moment
estimator with skip_internal_scaling = TRUE. They do not
invoke the simulation’s alternative internal latent-SD standardization
or alpha-search variants.
The simulation’s vh_study2.R applies the generating
population slope SD after estimation. For the bundled predictor case
that known SD is 0.8:
reported <- actual * case$reporting_scale
rbind(package = reported, population_SD_reference = case$reported_focal)
#> estimate se ci_low ci_high
#> package 0.7380259 0.1245395 0.493933 0.9821187
#> population_SD_reference 0.7380259 0.1245395 0.493933 0.9821187
stopifnot(isTRUE(all.equal(reported, case$reported_focal, tolerance = 1e-5)))Estimates, SEs, and both CI endpoints must be scaled together. An empirical application does not have a known generating population SD; do not substitute the SD of noisy predictions without defining the intended estimand. The package performs no automatic standardization.
All inference here remains conditional on fitted MLM parameters, uses
the model-based normal-error covariance, and assumes independent
analysis people. Adding nlme support does not change those assumptions
or propagate first-stage parameter uncertainty. Provenance and
regeneration instructions are in the bundled
extdata/README.md and the repository’s
dev/nlme-validation.md.