Skip to contents

Fit a relationship between two processes

Each MLM estimates a person’s random effects from repeated observations. Random-Effect Prediction Adjustment for Inference in Regression (REPAIR) fits a structural regression using their likelihood-only predictions and sampling-error covariance. For example, one process’s slope can predict another process’s slope, adjusting for the first process’s intercept. The two MLMs may use different occasions and grouping column names. Their ID values must identify the same units; REPAIR cannot infer an ID crosswalk.

This example uses packaged synthetic observations and frozen reference results from the paper’s simulation functions. It reproduces the dual-process computation, not the published Monte Carlo tables. Ordinary use supplies your own fitted models and unit-level data; no fixture is needed.

reference <- readRDS(system.file("extdata", "multimodel-workflow-reference.rds",
                               package = "repair"))
case <- reference$cases$independent
models <- list(
  growth = nlme::lme(y ~ z, random = ~ z | id, data = case$a),
  response = nlme::lme(q ~ w, random = ~ w | subject, data = case$b)
)
repair_effects(models)
#>      model   group        term n_levels
#> 1   growth      id (Intercept)       70
#> 2   growth      id           z       70
#> 3 response subject (Intercept)       70
#> 4 response subject           w       70
structural <- re("w", "response") ~
  re("(Intercept)", "growth") + re("z", "growth")
fit <- repair(structural, models, case$people, id = "person",
              cross_model_error = "independent")
summary(fit)
#> REPAIR structural regression
#> re("w", "response") ~ re("(Intercept)", "growth") + re("z", "growth") 
#> Units: 70 analyzed / 70 requested; 0 excluded
#> MLM: response (nlme; group subject; 0 IDs outside scope)
#> nlme singularity is not assessed; inspect the MLM fit and its fitting warnings.
#> MLM: growth (nlme; group id; 0 IDs outside scope)
#> nlme singularity is not assessed; inspect the MLM fit and its fitting warnings.
#> Cross-model prediction errors: assumed independent (zero covariance)
#> Predictions: likelihood-only random deviations
#>     model   group        term      role
#>  response subject           w   outcome
#>    growth      id (Intercept) predictor
#>    growth      id           z predictor
#> 
#> Posterior reliability (structural scope; equal unit weights):
#>     model        term      role      measure reliability n_units n_defined
#>  response           w   outcome     marginal       0.798      70        70
#>  response           w   outcome residualized       0.766      70        70
#>    growth (Intercept) predictor     marginal       0.889      70        70
#>    growth           z predictor     marginal       0.826      70        70
#>    growth           z predictor residualized       0.690      70        70
#> 
#>                                      estimate     se    zstat      pval  ci_low
#> (Intercept)                          0.009227 0.1082  0.08526 9.321e-01 -0.2029
#> re("(Intercept)", model = "growth") -0.109132 0.1447 -0.75427 4.507e-01 -0.3927
#> re("z", model = "growth")            0.910702 0.1921  4.73993 2.138e-06  0.5341
#>                                     ci_high
#> (Intercept)                          0.2213
#> re("(Intercept)", model = "growth")  0.1744
#> re("z", model = "growth")            1.2873
#> 
#> Regularization (preliminary / final): minimum / minimum 
#> Error-moment subtraction multipliers: 0.9429 / 0.9429 
#> Largest analysis-weight fraction: 0.0195 ; weight-equivalent count: 65.2 
#> Moment conditioning and unit weights: repair_diagnostics(fit).
#> Conditional on fitted MLM parameters; model-based normal SEs and intervals.

re("z", "growth") selects the growth model’s random slope for z; it is a deviation from its fixed slope. repair_effects() lists available scalar names. repair_data() performs the same assembly as repair() without fitting the structural regression, allowing you to inspect predictions and error inputs first.

Choose a prediction-error assumption

The cross_model_error argument is required when the formula references multiple models. It is not required merely because an unused model is in the supplied list.

  • "independent" sets all between-model prediction-error covariances to zero. It retains all within-model covariances, including intercept/slope covariance.
  • A list of named covariance blocks supplies the between-model covariances. Every unordered pair of referenced models must have a block, even if it is zero.
  • NULL, the default, is accepted only for a single referenced model.

Correlated latent slopes do not necessarily have correlated prediction errors. Conversely, separate MLM fits do not establish independent errors. Shared occasion-level disturbances or overlapping measurements can correlate the errors. Choose the policy from the measurement design and a defensible covariance model. The package does not estimate that covariance from separate fitted models.

Where do these covariances come from?

The target is the covariance of the estimation errors in the likelihood-only predictions, conditional on fitted measurement parameters. It is different from the covariance between people’s true intercepts/slopes. Correlating extracted slopes across people mixes true between-person variation with prediction error; it does not estimate the needed error covariance.

Start with the measurement design:

Design or evidence Practical action
Defensible independent measurement errors, conditional on each process’s target effects Use "independent", and state why. Sharing people alone does not contradict this assumption.
Paired occasions with plausible shared noise Specify an observation-level cross-error model and propagate it with repair_cross_covariance(). Examine a range of justified assumptions with repair_sensitivity().
Calibration data or a jointly fitted multivariate measurement model Obtain compatible observation error covariances from that source, separating residual/nuisance covariance from target random-effect covariance. Supply the observation blocks or externally propagated prediction blocks.
Insufficient evidence to choose one covariance Report sensitivity over a scientifically plausible range. The package cannot turn unidentified assumptions into empirical estimates.

Separate fits do not demonstrate independent errors. Different occasions do not guarantee independence either: persistent or serially correlated disturbances can bridge occasions. Conversely, correlated latent processes do not by themselves require nonzero cross-error blocks. The relevant assumption concerns the noise remaining after the target random coefficients are separated out.

Ordinary mixed-model residual correlations are not an automatic solution. For example, nlme::residuals() depends on the chosen grouping level and residual type; conditional residuals also reflect estimation and shrinkage of random effects. They are not interchangeable with observation errors or prediction errors. See the nlme residual documentation. A joint multivariate measurement model can distinguish residual correlations from cross-process random-effect correlations; the brms multivariate guide illustrates that distinction. REPAIR does not directly accept brms fits: an external covariance source must be compatible with the supported marginal fits, measurement scales, IDs, occasions, and effective nuisance covariance.

Each model must select one target grouping factor. lmer models can also have nuisance groups contained within each target person; see vignette("nested-nuisance"). Multiple models do not relax the independent-person assumption: shared nuisance groups remain rejected because their cross-person error covariance cannot enter this estimator. Models may mix supported lmer and single-group lme backends.

Supply nonzero cross-model covariance

Each block has models = c("a", "b") and a numeric covariance array with three dimensions: selected coefficient names from a, selected coefficient names from b, and unit IDs. All dimensions must be named. These are covariances in prediction units, not correlations, BLUP posterior covariances, or raw residual covariances. Names come from repair_effects() and the unit-level ID column.

For linear prediction extraction operators L_a and L_b, an externally justified residual cross-covariance R_ab gives prediction covariance L_a R_ab L_b-transpose. Deriving R_ab and matching the repeated observations is an analyst responsibility. This fixture uses a known residual correlation of 0.25 and fitted marginal residual scales; its generator performs that propagation independently of this package.

correlated <- reference$cases$supplied
models2 <- list(
  growth = nlme::lme(y ~ z, random = ~ z | id, data = correlated$a),
  response = nlme::lme(q ~ w, random = ~ w | subject, data = correlated$b)
)
# Prepared externally by the fixture generator, not inferred from the two fits.
score_cross_covariance <- correlated$cross_model_error[[1]]$covariance
dim(score_cross_covariance)  # 2 growth coefficients x 1 response coefficient x 70 IDs
#> [1]  2  1 70
dimnames(score_cross_covariance)[1:2]
#> [[1]]
#> [1] "(Intercept)" "z"          
#> 
#> [[2]]
#> [1] "w"
blocks <- list(list(models = c("growth", "response"),
                    covariance = score_cross_covariance))
fit2 <- repair(structural, models2, correlated$people, "person",
               cross_model_error = blocks)
head(fit2@analysis_data@err_xy)
#>     re("(Intercept)", model = "growth") re("z", model = "growth")
#> p01                         -0.05797162                0.07729549
#> p02                         -0.04508904                0.05153033
#> p03                         -0.03607123                0.03607123
#> p04                         -0.02951282                0.02623362
#> p05                         -0.07729549                0.12367278
#> p06                         -0.05797162                0.07729549
summary(fit2)$cross_model_error$policy
#> [1] "supplied"

Term names must exactly cover the coefficients selected by the formula, not necessarily every coefficient in the fitted model. Every retained person must have a block entry; extra IDs are permitted. Row, column, ID, model-list, and block ordering do not matter. Reversing a pair requires transposing its first two array dimensions. Supply a pair only once; REPAIR supplies its transpose. Within-model error blocks are computed by prediction extraction and cannot be overridden. The complete assembled covariance must be positive semidefinite for each person; checking pairs separately would be insufficient for three or more models.

The policy and original supplied blocks remain in fit@analysis_data@diagnostics$cross_model_error and summary(fit)$cross_model_error. The estimator’s final aligned inputs are @err_x, @err_y, and @err_xy. Standard errors condition on the MLM fits and supplied covariance; they do not propagate uncertainty in estimating either.

Propagate observation covariance with a helper

repair_cross_covariance() computes the extraction operators from the fitted models and propagates supplied observation error assumptions:

La,i=(Za,i𝖳Ra,i−1Za,i)−1Za,i𝖳Ra,i−1,Ωab,i=La,iRab,iLb,i𝖳. L_{a,i} = (Z_{a,i}^{\mathsf T}R_{a,i}^{-1}Z_{a,i})^{-1} Z_{a,i}^{\mathsf T}R_{a,i}^{-1}, \qquad \Omega_{ab,i} = L_{a,i}R_{ab,i}L_{b,i}^{\mathsf T}.

Here R_a and R_b are the fitted effective error covariances used by the scorer, including contained nuisance random effects when present; they exclude the target random effects. R_ab describes covariance between those effective observation errors. Only the formula-selected coefficients are returned. The helper does not refit a joint model or estimate R_ab.

Matched occasions under an assumed iid correlation

For two models with homoscedastic iid errors and no nuisance random groups, the rho shortcut assumes correlation rho at matching occasions for the same person, and zero covariance at all other occasion pairs. This fixture has known matching time scales: z = time / 4 and w = 0.5 + time / 5. Its generating rho = 0.25 is known only because the data are synthetic; this is not an empirical estimate.

# Values are occasion keys, names identify original observation rows.
# Real data should use recorded visit/occasion identifiers, on a common scale.
keys <- list(
  growth = setNames(as.character(round(4 * correlated$a$z)), rownames(correlated$a)),
  response = setNames(as.character(round(5 * (correlated$b$w - .5))),
                      rownames(correlated$b))
)
propagated <- repair_cross_covariance(structural, models2, keys,
  rho = .25, ids = correlated$people$person)
fit_propagated <- repair(structural, models2, correlated$people, "person",
                         cross_model_error = propagated)
# The frozen reference uses marginal scales from its original native fits.
# Refitted scales can vary slightly across optimizer/package/platform versions.
stopifnot(isTRUE(all.equal(coef(fit_propagated), coef(fit2), tolerance = 1e-5)),
          isTRUE(all.equal(vcov(fit_propagated), vcov(fit2), tolerance = 1e-5)))

Keys are matched to effective fitted row names, so original input order, subsetting and omitted rows do not silently change alignment. Supply unique, nonempty occasion keys within each person and model; they can repeat between people. Equal keys identify equal occasions across models. Preserve the original row names in the key vectors. The helper never pairs by row position or nearest time. Unmatched occasions have zero cross-covariance under this shortcut, an assumption that needs justification for your design. The shortcut rejects correlated or heterogeneous marginal errors; a plausible scalar rho alone is insufficient to specify a joint covariance for those models.

Explicit observation blocks

For more general errors, supply a matrix R_ab for every requested person and every unordered pair of referenced models. Matrix row and column names identify effective occasion keys in the two models; these matrices may be rectangular. The following explicitly constructs the same iid assumption for illustration:

observation_covariance <- lapply(correlated$people$person, function(person) {
  a <- keys$growth[rownames(correlated$a)[correlated$a$id == person]]
  b <- keys$response[rownames(correlated$b)[correlated$b$subject == person]]
  rab <- outer(unname(a), unname(b), `==`) * .25 *
    sigma(models2$growth) * sigma(models2$response)
  dimnames(rab) <- list(a, b)
  rab
})
names(observation_covariance) <- correlated$people$person
explicit <- repair_cross_covariance(structural, models2, keys,
  residual_cross_covariance = list(list(models = c("growth", "response"),
    covariance = observation_covariance)), ids = correlated$people$person)
stopifnot(isTRUE(all.equal(explicit, propagated, tolerance = 1e-12)))
fit_explicit <- repair(structural, models2, correlated$people, "person",
                       cross_model_error = explicit)
# Both calculations now use exactly the same fitted marginal scales.
stopifnot(isTRUE(all.equal(coef(fit_explicit), coef(fit_propagated), tolerance = 1e-12)),
          isTRUE(all.equal(vcov(fit_explicit), vcov(fit_propagated), tolerance = 1e-12)))

In a real analysis, replace those matrices with a scientifically justified joint error model or compatible external calibration. Their entries are observation covariances, not correlations. For nested nuisance groups, include any cross-model nuisance covariance in addition to residual covariance. Automatic estimation from paired residuals would need its own statistical method and validation and is outside this workflow.

The helper checks the complete joint observation covariance using fitted within-model blocks, then checks the propagated selected-effect covariance. With three or more models, valid pairs need not form a valid joint covariance. It rejects invalid inputs rather than projecting them to a nearby matrix. The fitted marginal blocks are preserved. Incompatible external estimates must be reconciled through the measurement model, not silently modified here.

Examine sensitivity to the cross-error assumption

Choose a range from substantive knowledge of the measurement errors, calibration, or external studies. The values below are illustrative and not a recommended universal range. A sensitivity grid is not a confidence interval for rho, and choosing the scenario with the preferred structural result would undermine its purpose. Keep other fitting choices and the analysis scope fixed.

rhos <- c(-.5, 0, .25, .5)
scenario_names <- paste0("rho=", rhos)
constructed <- setNames(vector("list", length(rhos)), scenario_names)
construction <- data.frame(scenario = scenario_names, rho = rhos,
                           status = "ok", message = "")
for (j in seq_along(rhos)) {
  # Preserve construction failures as well as downstream fitting failures.
  constructed[j] <- list(tryCatch(
    repair_cross_covariance(structural, models2, keys, rho = rhos[j],
                             ids = correlated$people$person),
    error = function(e) {
      construction$status[j] <<- "error"
      construction$message[j] <<- conditionMessage(e)
      NULL
    }))
}
construction
#>   scenario   rho status message
#> 1 rho=-0.5 -0.50     ok        
#> 2    rho=0  0.00     ok        
#> 3 rho=0.25  0.25     ok        
#> 4  rho=0.5  0.50     ok
scenarios <- c(list(independent = "independent"),
               constructed[construction$status == "ok"])
sensitivity <- repair_sensitivity(structural, models2, correlated$people,
  "person", scenarios = scenarios, regularization = "step_up")
sensitivity$scenarios  # status, warnings, selected alphas, fallback flags
#>      scenario status message warnings nobs alpha_preliminary alpha_final
#> 1 independent     ok      ok            70                 4           4
#> 2    rho=-0.5     ok      ok            70                 4           4
#> 3       rho=0     ok      ok            70                 4           4
#> 4    rho=0.25     ok      ok            70                 4           4
#> 5     rho=0.5     ok      ok            70                 4           4
#>   fallback_preliminary fallback_final
#> 1                FALSE          FALSE
#> 2                FALSE          FALSE
#> 3                FALSE          FALSE
#> 4                FALSE          FALSE
#> 5                FALSE          FALSE
sensitivity$coefficients[, c("scenario", "term", "estimate", "std.error",
                             "conf.low", "conf.high")]
#>       scenario                                term    estimate  std.error
#> 1  independent                         (Intercept) -0.01676368 0.08688612
#> 2  independent re("(Intercept)", model = "growth") -0.28032476 0.10393400
#> 3  independent           re("z", model = "growth")  0.31281465 0.11012060
#> 4     rho=-0.5                         (Intercept) -0.02471867 0.08779144
#> 5     rho=-0.5 re("(Intercept)", model = "growth") -0.41402024 0.11185684
#> 6     rho=-0.5           re("z", model = "growth")  0.46452461 0.12094014
#> 7        rho=0                         (Intercept) -0.01676368 0.08688612
#> 8        rho=0 re("(Intercept)", model = "growth") -0.28032476 0.10393400
#> 9        rho=0           re("z", model = "growth")  0.31281465 0.11012060
#> 10    rho=0.25                         (Intercept) -0.01556387 0.08716192
#> 11    rho=0.25 re("(Intercept)", model = "growth") -0.21373526 0.10274312
#> 12    rho=0.25           re("z", model = "growth")  0.23821450 0.10819416
#> 13     rho=0.5                         (Intercept) -0.01482731 0.08846792
#> 14     rho=0.5 re("(Intercept)", model = "growth") -0.14754824 0.10428021
#> 15     rho=0.5           re("z", model = "growth")  0.16317246 0.10964868
#>       conf.low   conf.high
#> 1  -0.18705734  0.15352998
#> 2  -0.48403165 -0.07661786
#> 3   0.09698223  0.52864706
#> 4  -0.19678673  0.14734939
#> 5  -0.63325561 -0.19478487
#> 6   0.22748628  0.70156293
#> 7  -0.18705734  0.15352998
#> 8  -0.48403165 -0.07661786
#> 9   0.09698223  0.52864706
#> 10 -0.18639809  0.15527035
#> 11 -0.41510807 -0.01236245
#> 12  0.02615785  0.45027115
#> 13 -0.18822124  0.15856662
#> 14 -0.35193370  0.05683722
#> 15 -0.05173500  0.37807992
# Inspect full diagnostics for a particular assumption.
repair_diagnostics(sensitivity$fits[["rho=0.25"]], table = "conditioning")
#>          step dimension min_eigenvalue max_eigenvalue condition_number
#> 1 preliminary         3       52.52542       87.76887         1.670979
#> 2       final         3       84.64164      174.01153         2.055862
stopifnot(identical(sensitivity$fits$independent@struc_fit,
                    sensitivity$fits[["rho=0"]]@struc_fit))

The models are reused across scenarios; repair_mlm() specifications, if supplied, are fitted once for the whole sensitivity call. Each scenario uses the existing estimator and reselects step-up alphas when requested. Scenario-specific invalid covariance inputs have status "error", numerical structural failures have status "failed", and neither produces coefficient rows. A usable minimum-alpha fallback remains "ok" with explicit fallback flags. Shared input errors stop the call. Warnings during each scenario are saved in its summary. Construction failures occur before repair_sensitivity(), so keep the construction table alongside its outputs, as above.

Report the assumptions, admissible range, rejected or failed scenarios, and how the estimates, SEs, intervals, and regularization change. Intervals remain conditional on each assumed covariance and the fitted marginal model parameters. They do not average over scenarios or include uncertainty in an estimated error correlation. The existing whole-unit bootstrap supports a single measurement model; this sensitivity workflow does not add a multiple-model bootstrap or propagate uncertainty in externally estimated cross-model parameters.

Basic simulation evidence

A repeated-sampling screen accompanying PR #24 used 500 replicates in each of 48 paired iid Gaussian conditions, varying N (50/200), nominal occasions (6/12), balance, true cross-error correlation (-0.5/0/0.5), and a null/nonzero structural slope. With the correct covariance assumption, overall 95% interval coverage was 95.15% with fitted marginal models and 95.28% with known measurement parameters; condition-level coverage ranged from 93.2% to 97.2%. Near 95%, the condition-level Monte Carlo SE is approximately one percentage point.

Assuming independence when the true cross-error correlation was -0.5 or 0.5 produced pooled null-effect Type I error rates of 58.6% and 59.0% in these illustrative conditions. A valid covariance matrix need not encode a correct scientific assumption. This supports examining justified alternatives rather than selecting independence for convenience. It does not identify the true correlation or supply unconditional inference over unknown covariance parameters.

There were no fitting failures. All default step-up searches retained alpha 3, so this screen does not assess activated adaptive selection or fallback inference. The PR includes reproducible scripts and full condition-level tables; its findings are limited to this two-process, one-predictor iid design, not a general coverage guarantee or validation of automatic covariance estimation.

Check matching and exclusions

The unit-level data frame defines the scope and output order. Each model’s predictions are matched to it by ID. By default an absent ID, failed prediction, or missing/nonfinite observed structural variable stops assembly. With na_action = "omit", REPAIR warns and records the ID and all applicable reasons, including the responsible model names. It never matches by row position. Invalid covariance specifications are errors even with omission enabled.

a <- fit@analysis_data
a@diagnostics$excluded
#> [1] id     reason
#> <0 rows> (or 0-length row.names)
lapply(a@diagnostics$mlm_models, function(x) x$unused_prediction_ids)
#> $response
#> character(0)
#> 
#> $growth
#> character(0)
names(a@predictions)  # named by model for multiple-model analyses
#> [1] "response" "growth"
head(a@predictions$growth@predictions$id)
#>     (Intercept)          z
#> p01  -0.9181124 -1.8436453
#> p02   0.5495794 -0.2507799
#> p03  -0.6847968 -0.8040252
#> p04  -0.5183052 -0.4138292
#> p05  -0.5251184  0.6688866
#> p06   0.3182383 -0.8261096

For single-model analyses, @predictions remains the original prediction object. @diagnostics$mlm_models is always a named list, giving a consistent way to inspect grouping names, backend, unused IDs, singularity, and fit messages.

Reproduce coefficients, standard errors, and intervals

The frozen expectations were produced without loading repair, using the paper’s production prediction extraction helper, full M-MOM implementation, primary dual-process estimator, and independent algebra audit. Tests refit both MLMs from observations and compare both R and C++ computation backends.

stopifnot(isTRUE(all.equal(unname(coef(fit)), case$coefficients$estimate,
                          tolerance = 1e-5)))
stopifnot(isTRUE(all.equal(unname(vcov(fit)), unname(case$vcov),
                          tolerance = 1e-5)))
stopifnot(isTRUE(all.equal(unname(confint(fit)),
  unname(as.matrix(case$coefficients[, c("ci_low", "ci_high")])), tolerance = 1e-5)))
# The simulation reports a standardized focal slope using a population SD ratio.
# This known generating ratio is NOT the SD ratio of noisy estimated predictions.
focal <- tail(fit@struc_fit@coefficients, 1)[, c("estimate", "se", "ci_low", "ci_high")]
rownames(focal) <- NULL
reported <- focal * case$reporting_scale
reported
#>    estimate        se   ci_low  ci_high
#> 1 0.9194346 0.1939763 0.539248 1.299621
stopifnot(isTRUE(all.equal(reported, case$reported_focal, tolerance = 1e-5)))

The package estimates on the input scale. The paper’s dual-process reporting scale is population predictor-slope SD divided by population outcome-slope SD. Apply the same positive factor to the focal estimate, SE, and interval endpoints. For empirical analyses, choose and disclose a justified reporting scale; estimated scale uncertainty is not included by multiplying the output.

Fixture provenance records source commit and hashes, R/nlme versions, and the modified preliminary moment and final covariance bread. The source repository’s dev/generate_multimodel_fixtures.R and dev/multimodel-validation.md document the generation and validation workflow.