Skip to contents

mars_rf() provides three exploratory prediction workflows through mars_rf_univariate(), mars_rf_multivariate(), and mars_rf_multilevel(). They share the same tree-building algorithm:

  1. Sample whole studies (or outermost multilevel groups) with replacement. Repeated draws are independent copies of the entire sampling-covariance block.
  2. Select candidate moderators at each node by default and grow/prune using weighted squared error. selection = "tree" selects a subset once for the entire tree. Multivariate trees retain effect identity separately; it does not consume the mtry moderator budget. Child nodes must meet both the observation-size controls and min_studies distinct-group requirement.
  3. Refine terminal multivariate or multilevel leaves with covariance-aware GLS or marginal maximum likelihood. Estimate variance components using only that tree’s training observations.
  4. Average tree predictions and evaluate studies left out of each tree.

The default uses per-node candidate selection. The explicit tree option provides a random-subspace ensemble. Multivariate and multilevel terminal leaves include linear predictors, so these are model-tree ensembles rather than exact copies of ordinary regression forests. Off-diagonal sampling covariance and random effects enter terminal fitting; splits do not optimize a joint likelihood across the forest. The following examples show what each path estimates and how to inspect its limits.

Univariate Example

rf_uni <- mars_rf_univariate(
  data = teacher_expectancy,
  formula = yi ~ year + weeks + factor(setting) + factor(tester),
  studyID = "study",
  variance = "vi",
  varcov_type = "univariate",
  num_trees = 10,
  seed = 123
)

summary(rf_uni)
#> Random forest meta-analysis
#> Structure: univariate 
#> Trees: 10 
#> Predictor selection: node ; split weighting: sampling 
#> Predictors: year, weeks, factor.setting., factor.tester. 
#> OOB predictions hold out complete resampling units; preprocessing is conditional on the prepared predictor representation. 
#> OOB coverage: 94.7368 %
#> OOB RMSE: 0.1712 
#> OOB R-squared: 0.375 
#> 
#> Top variable importance:
#>        predictor importance
#>            weeks 0.30118326
#>   factor.tester. 0.01845478
#>             year 0.01810451
#>  factor.setting. 0.00000000
head(rf_importance(rf_uni))
#>         predictor importance
#> 2           weeks 0.89175397
#> 4  factor.tester. 0.05464156
#> 1            year 0.05360447
#> 3 factor.setting. 0.00000000
# Only predictors are needed; outcomes, variances and study IDs are unnecessary.
new_predictors <- teacher_expectancy[1:5, c("year", "weeks", "setting", "tester")]
predict(rf_uni, newdata = new_predictors)
#> [1] -0.025008286 -0.004716837 -0.025008286  0.248237367  0.245851391
length(predict(rf_uni, newdata = new_predictors[1, , drop = FALSE])) # one
#> [1] 1

rf_uni uses weighting = "sampling": inverse sampling variances. Alternatively, "uniform" gives each observation equal split-loss weight. Univariate-only "random" uses 1/(v_i+\widehat{\tau}^2), where heterogeneity is estimated by profiling the intercept-model ML likelihood separately within each bootstrap training sample. It is not estimated from held-out outcomes. With fewer than two distinct original studies, that tree uses sampling weights and reports weight_tau = NA. Inspect fit$forest[[tree]]$weight_tau.

These weighting choices affect partitioning and univariate leaf means. Multilevel and multivariate terminal covariance fits retain the specified sampling covariance and their own ML/GLS mean models. Importance measures the mean reduction in the tree’s weighted split loss. It is not a coefficient, p-value, or causal effect.

Multivariate Example

rf_multi <- mars_rf_multivariate(
  data = becker09,
  studyID = "ID",
  effectID = "numID",
  sample_size = "N",
  effectsize_type = "cor",
  varcov_type = "weighted",
  variable_names = c(
    "Cognitive_Performance",
    "Somatic_Performance",
    "Selfconfidence_Performance",
    "Somatic_Cognitive",
    "Selfconfidence_Cognitive",
    "Selfconfidence_Somatic"
  ),
  multivariate_covs = ~ Team,
  num_trees = 10,
  seed = 123
)

summary(rf_multi)
#> Random forest meta-analysis
#> Structure: multivariate 
#> Trees: 10 
#> Predictor selection: node ; split weighting: sampling 
#> Predictors: effect_id, Team 
#> OOB predictions hold out complete resampling units; preprocessing is conditional on the prepared predictor representation. 
#> Leaf fits with fallback: 2 
#> OOB coverage: 100 %
#> OOB RMSE: 0.2928 
#> OOB R-squared: 0.5411 
#> 
#> Top variable importance:
#>  predictor importance
#>  effect_id 6.95623811
#>       Team 0.09713254
head(rf_importance(rf_multi))
#>   predictor importance
#> 1 effect_id 0.98622892
#> 2      Team 0.01377108
predict(rf_multi, newdata = rf_multi$data[1:6, , drop = FALSE])
#> [1] -0.04152935 -0.16305344  0.37184346  0.46662825 -0.37494006 -0.44929777

Each multivariate leaf estimates a mean model with effect-type contrasts and selected predictors. ML estimates outcome-specific diagonal heterogeneity; GLS uses the within-study sampling covariance if variance estimation is not supported or fails. Inspect the estimator and reason for every fallback:

head(rf_multi$fit_diagnostics)
#>   estimator convergence rank n studies diagnostic tree
#> 1        ML           0    2 8       4               1
#> 2        ML           0    2 8       4               1
#> 3        ML           0    2 8       4               1
#> 4        ML           0    2 8       4               1
#> 5        ML           0    2 8       4               1
#> 6        ML           0    2 8       4               1

Correlation inputs are raw correlations with covariance types simple, weighted, or average (their cor_ aliases are supported). By default, prediction_scale = "fisher_z" transforms responses as z=\operatorname{atanh}(r) and sampling covariance as S_z=J S_r J^\top, with J_{ii}=1/(1-r_i^2). Predictions average trees on the working scale and return \tanh(\widehat z). This is a back-transformed fitted location, not the raw-scale expectation integrated over random effects. prediction_scale = "raw" fits raw correlations directly and may extrapolate outside [-1,1]. Neither pairwise bounds nor Fisher-z fitting guarantee a valid joint correlation matrix. For pooled covariance types, covariance estimation is repeated within each bootstrap sample. Changing the outcomes of an OOB study cannot change that tree’s training covariance. Correlation input requires one matrix per study; multivariate long-form SMD input requires distinct effect IDs within each study.

Multilevel Example

rf_multi_level <- mars_rf_multilevel(
  data = school,
  formula = effect ~ year + (1 | district/study),
  studyID = "district",
  variance = "var",
  varcov_type = "multilevel",
  num_trees = 10,
  seed = 123
)

summary(rf_multi_level)
#> Random forest meta-analysis
#> Structure: multilevel 
#> Trees: 10 
#> Predictor selection: node ; split weighting: sampling 
#> Predictors: year 
#> OOB predictions hold out complete resampling units; preprocessing is conditional on the prepared predictor representation. 
#> Leaf fits with fallback: 3 
#> OOB coverage: 100 %
#> OOB RMSE: 0.4499 
#> OOB R-squared: -3.1396 
#> 
#> Top variable importance:
#>  predictor importance
#>       year  0.6771927
rf_multi_level$random_tau
#>   district      study 
#> 0.04602168 0.03044551
predict(rf_multi_level, newdata = school[1:5, , drop = FALSE])
#> [1] 0.04728023 0.04615754 0.05761929 0.04510113 0.05060776

Known and New Groups

Multilevel RF currently supports one nested random-intercept term, such as (1 | district/study). studyID must identify the outermost group. A study label reused in two districts represents two different nested groups. Random slopes and crossed random terms are rejected rather than silently simplified.

Known groups receive leaf-specific BLUP contributions where that group was observed during training. Use re_form = "conditional" for these contributions or re_form = "population" to explicitly omit every BLUP. New groups, or predictions with no group IDs, receive zero random-effect contributions:

predict(rf_multi_level, newdata = school[1:5, , drop = FALSE], re_form = "population")
#> [1] 0.08535233 0.08535233 0.08535233 0.08535233 0.03471904
rf_multi_level$forest[[1]]$sampled_units
#>  [1] "12" "12" "86" "11" "56" "91" "27" "18" "56" "71" "86"
rf_multi_level$forest[[1]]$inbag_counts
#> 
#> 108  11  12  18  27  56  58 644  71  86  91 
#>   0   1   2   1   1   2   0   0   1   2   1

random_tau summarizes the median tree-root variance estimates. It is not a single full-data heterogeneity estimate and has no confirmatory confidence interval. Only roots that successfully estimate variance components contribute; unsupported or failed roots are excluded, and all-unavailable components are NA. Root-fit diagnostics are available in rf_multi_level$forest[[1]]$root_diagnostic.

What Is Optimized?

The split and pruning criterion is

L(A) = \sum_{i\in A} w_i (y_i-\bar y_{w,A})^2,

where weights follow the selected weighting option. For correlation forests, both response and covariance are on the selected fitting scale. Uniform weights apply to observations; studies reporting more effects can still contribute more split loss. min_studies counts distinct original groups, not bootstrap copies. cp is a fraction of the root loss. Predictor-unit changes, such as meters to centimeters, do not alter the partition criterion. Importance aggregates reductions from splits retained after pruning, averaged over trees.

For a terminal covariance model, ML minimizes

\log|V|+(y-X\beta)^\top V^{-1}(y-X\beta),

profiling \beta by GLS and constraining variance components to be nonnegative. Multilevel V includes sampling covariance and nested random-intercept covariance. The residual here is the marginal residual y-X\beta; BLUPs enter prediction after fitting. ML leaf objective values are never compared with split loss or used as forest-wide likelihood tests.

Singular predictor designs are reduced to an estimable column basis. fit_diagnostics distinguishes ML, GLS_fallback for optimization failures, and GLS_insufficient for inadequate distinct studies/residual degrees of freedom or indistinguishable variance components. Both GLS statuses are counted in the summary. A GLS status means that variance components were unavailable, not that heterogeneity was successfully estimated as zero. Always inspect these statuses before interpretation.

Missing Predictors and Prediction

  • missing = "remove" removes rows missing required outcomes, sampling inputs or moderators. For wide correlation input this removes the whole study matrix. Nonmissing invalid variances are rejected.
  • missing = "keep" permits missing predictors; outcomes, sample sizes and variances must remain valid. It learns a missing-value direction at each split. Missing rows contribute to both the parent and their assigned child’s loss. Terminal linear prediction uses the leaf’s training median/modal fill values.
  • missing = "em" retains the supported continuous-moderator EM workflow, but OOB results are unavailable after this full-data completion. Use external grouped validation with imputation fitted inside each training fold. New continuous prediction rows are completed using frozen training conditional means and covariance; the prediction batch does not refit the imputer. Missing categorical prediction moderators are unsupported.

Sampling variances must be finite and strictly positive. Invalid or indefinite sampling covariance is rejected; it is not converted to artificial precision. Unknown predictor factor levels are rejected, while previously unseen random group IDs are allowed and receive zero random effects.

Training terms preserve supported R prediction transformations, including scale() and poly(). Predictions do not refit these transformations on the prediction batch. Custom data-adaptive transformations need an appropriate makepredictcall method or an externally fitted transformation applied to both training and prediction data.

OOB Evaluation and Interpretation

c(coverage = rf_uni$oob_coverage, RMSE = rf_uni$oob_rmse, R2 = rf_uni$oob_r2)
#>  coverage      RMSE        R2 
#> 0.9473684 0.1712331 0.3749595
table(rf_uni$oob_counts)
#> 
#> 0 1 2 3 4 5 
#> 1 1 3 5 5 4
rf_uni$oob_note
#> [1] "OOB predictions hold out complete resampling units; preprocessing is conditional on the prepared predictor representation."

OOB counts indicate how many trees evaluated each observation without training on its resampling unit. Increase the number of trees if coverage is poor. These errors estimate performance on unseen studies/groups conditional on the prepared predictor representation. Tuning, feature engineering and imputation should be evaluated with a separate grouped validation procedure.

Split importance does not include the additional predictive contribution of terminal linear coefficients. Zero split importance therefore does not prove that a variable is irrelevant. Importance can also favor predictors offering many candidate splits, and correlated predictors can share importance. Use stability checks and held-out prediction comparisons for substantive claims. For confirmatory model estimates and inference, use mars() and its likelihood-based methods.

Correlation Matrix Predictions

Provide the internal effect and group identifiers named by effect_id and study_id. Each matrix prediction must contain every effect ID exactly once. type = "working" returns working-scale values; type = "response" returns effect-scale values; type = "matrix" returns named correlation matrices.

first_group <- rf_multi$data$study[1]
matrix_data <- rf_multi$data[rf_multi$data$study == first_group, , drop = FALSE]
matrices <- predict(rf_multi, matrix_data, type = "matrix", matrix_action = "none")
attr(matrices, "diagnostics")
#>   group valid_before min_eigenvalue_before repaired max_abs_change
#> 1     1         TRUE             0.4869469    FALSE              0
#>   min_eigenvalue_after
#> 1            0.4869469

The default matrix_action = "warn" reports invalid complete predicted matrices. "error" refuses invalid predictions. "none" retains results for inspection. Only explicit "repair" applies a nearest positive-definite correlation matrix projection via the already imported Matrix package. Its diagnostics record the original and final minimum eigenvalues and maximum absolute change. Repair is a post-processing decision, changes estimates, and provides no inferential correction. Incomplete sets of predicted pairs cannot be repaired.

repaired <- predict(rf_multi, matrix_data, type = "matrix", matrix_action = "repair")
attr(repaired, "diagnostics")
#>   group valid_before min_eigenvalue_before repaired max_abs_change
#> 1     1         TRUE             0.4869469    FALSE              0
#>   min_eigenvalue_after
#> 1            0.4869469

Complete Grouped Validation and Permutation Importance

mars_rf_validate() refits the entire workflow within training folds, holding out complete studies or outermost multilevel groups. Formula transformations, covariance pooling, EM moments and heterogeneity weights are learned inside the training fold. Multilevel evaluation uses population predictions for new groups. Evaluation errors use inverse raw sampling variances on the response scale, regardless of training split weighting. This targets precision-weighted prediction of observed effect estimates, not an unbiased estimate of error for latent true effects. It may emphasize studies reporting more precise or more numerous effects.

validation_fit <- mars_rf_univariate(
  teacher_expectancy, yi ~ year + weeks, "study", "vi",
  num_trees = 10, seed = 123
)
validation <- mars_rf_validate(
  validation_fit, folds = 3, seed = 124, permutation_repeats = 3
)
validation$metrics
#>      rmse        r2 
#> 0.1989331 0.1694748
validation$coverage
#> [1] 1
validation$folds
#>   fold groups status reason
#> 1    1      7     ok       
#> 2    2      6     ok       
#> 3    3      6     ok
rf_importance(validation_fit, type = "permutation", validation = validation)
#>   predictor    importance evaluated_folds requested_folds
#> 1      year -0.0005645523               3               3
#> 2     weeks  0.0193707827               3               3

Permutation importance is the increase in held-out weighted squared error when a moderator is permuted between independent groups. It includes changes in terminal linear predictions. Study-invariant predictors move as whole group-level values. Within-group varying predictors move as whole vectors only when held-out groups have equal sizes; unequal sizes make that importance unavailable. Such permutations require exchangeable groups and compatible within-group observation ordering. With EM, permutations act on the completed held-out moderators. Negative values are possible; importance is not a p-value, causal effect or significance test.

Multivariate fits provide oob_by_effect; validation provides by_effect. A pooled R-squared can reflect differences in outcome means, so inspect each outcome separately. Fold failures (for example, an unsupported categorical level) are reported rather than replaced by training predictions. Coverage and successful folds must be inspected before interpreting pooled scores. Validation conditions on the supplied tuning choices; using these results to select models requires a separate outer validation loop.

Formula and Input Rules

Parentheses retain ordinary terms, such as yi ~ year + (weeks). Transformed response expressions are evaluated in data, and explicit interactions also enter terminal linear models as derived predictors. Random terms are valid only in the multilevel workflow, which supports one nested random-intercept term. Specify moderators explicitly rather than using a dot formula that can include outcomes or identifiers. Outcome variables cannot also be predictors. Unused arguments and unsupported structure labels are errors.

For correlation input, supplied moderators are retained exactly once. Names such as ri, study, numID, Variable1 and Variable2 conflict with generated fields and must be renamed before fitting; N is valid when it is the sample-size column. Inspect candidate_predictors, study_id and effect_id before predicting.