| Title: | Meta Analysis and Research Synthesis |
| Version: | 0.6.1 |
| Description: | Tools for meta-analysis and research synthesis, including univariate, multivariate, multilevel, and network meta-analysis. Supports effect-size computation and transformation, construction of within-study sampling variance-covariance matrices, meta-regression, and synthesis of dependent and repeated effects. Additional methods include path and factor modeling following correlation synthesis, penalized meta-regression, and exploratory random-forest meta-analysis. Provides model diagnostics, robust inference, publication-bias assessment and adjustment, resampling and sensitivity analyses, and graphics and reporting tools for evidence synthesis. For background, see Cooper, Hedges, and Valentine (2019) <doi:10.7758/9781610448864> and Schmid, Stijnen, and White (2020) <doi:10.1201/9781315119403>. |
| URL: | https://mars.brandonlebeau.org/ |
| Depends: | R (≥ 4.2) |
| Imports: | Matrix, matrixcalc, future.apply |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| LazyData: | true |
| Suggests: | knitr, rmarkdown, future, testthat (≥ 3.0.0) |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| Config/roxygen2/version: | 8.1.0 |
| Config/Needs/website: | meta, metabook, netmeta |
| Config/Needs/benchmarks: | pkgload, testthat, meta, netmeta, metaSEM, lavaan, metafor, mvtnorm, polycor, clubSandwich, mada |
| NeedsCompilation: | no |
| Packaged: | 2026-12-01 19:27:08 UTC; blebeau |
| Author: | Brandon LeBeau |
| Maintainer: | Brandon LeBeau <lebebr01+mars@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-12-01 20:10:15 UTC |
MARS: Meta Analysis and Research Synthesis
Description
MARS fits meta-analytic models for independent and dependent effect sizes. It covers the analysis from effect-size construction and covariance specification through estimation, inference, diagnostics, and reporting. It also provides specialized models for treatment networks, repeated effects, diagnostic accuracy, and correlation synthesis.
Effect sizes and dependence
Start with compute_es() to calculate effect sizes and sampling variances
from study summaries. Use es_methods() to see the supported measures and
transform_es() to change effect scales where a conversion is available.
Distinguish sampling covariance from heterogeneity. Sampling covariance
describes how estimation errors are related, for instance when two effects
share a control group. Heterogeneity describes how the underlying true
effects vary. Use compute_es_covariance() to construct sampling covariance
blocks for supported designs. In mars(), varcov_type selects the
sampling covariance construction and structure specifies the
heterogeneity model. The model uses both to weight the evidence.
Core meta-analytic models
- Univariate synthesis and meta-regression
Use
mars()with a formula for a pooled mean or to relate effects to moderators. Ordinary fits default to restricted maximum likelihood (REML). Maximum likelihood is available. In a univariate model,tau2 = 0fits a common-effect model, and other fixed values support sensitivity analysis.- Multivariate synthesis
Jointly pool several outcomes or the entries of study correlation matrices. Choose an unstructured between-study covariance, outcome-specific variances with zero covariance, or one common diagonal variance. A diagonal heterogeneity model can still account for correlated sampling errors within a study.
- Multilevel synthesis
Use random-effect terms in
formulato model variation at different levels, such as effects within studies and studies within districts.- Location-scale meta-regression
Use
scale_formulato model how log heterogeneity varies with moderators in supported univariate and multilevel fits. The mean formula specifies how the expected effect changes. The scale formula specifies how much true effects vary.
Specialized models
- Repeated effects
Use
mars_repeated()for effects measured across outcomes, groups, or follow-up times. It constructs study blocks from explicit working assumptions, such as AR(1) dependence over time or a correlation for effects sharing a control. The mean can vary by outcome, group, time, or supported combinations.- Treatment networks
Use
network_meta()to estimate relative treatment effects jointly from direct and indirect evidence under coherence. Choose common-effect weighted least squares or a joint model with a heterogeneity structure suited to the design. Use repeated network models when comparisons span outcomes or times. Use node splitting and design incoherence tests to investigate disagreement across sources of evidence.- Diagnostic accuracy
Use
mars_dta()to pool sensitivity and specificity jointly. It supports Gaussian models of study logits and a binomial model for the original counts. Usemars_dta_paired()for two tests applied to the same participants, ormars_dta_thresholds()for one test evaluated at multiple cutoffs. Both support Gaussian and multinomial models. The threshold multinomial model gives monotone predictions across cutoffs.- Correlation, path, and factor models
After pooling correlations with
mars(), usepath_model(),efa_from_synthesis(), orcfa_from_synthesis()for a downstream analysis. These workflows can propagate uncertainty from the pooled correlations where supported. Use mixed correlation analysis to estimate associations among effect sizes and moderators across studies.- Moderator and bias analyses
Use
masmr()to compare methodology-only and joint meta-regressions,mars_lasso()for penalized moderator selection, ormars_rf()to explore nonlinear prediction and variable importance. LASSO and forests provide their own summaries. Ordinary coefficient tests do not account for moderator selection. Usepublication_bias()to assess sensitivity to a specified publication-selection model.
Choosing coefficient inference
For supported fits, choose inference in summary() after estimation.
This changes uncertainty estimates, tests, or intervals for the mean
coefficients while leaving the fitted coefficients and heterogeneity
estimates in place. Use matching options in confint() for ordinary
MARS and coherent network fits.
- Model-based Wald tests
Normal tests use the model covariance and a standard normal reference distribution. For eligible independent univariate fits,
test = "t"uses residual degrees of freedom with the same covariance.- Hartung-Knapp-Sidik-Jonkman (HKSJ)
For independent univariate models with constant heterogeneity estimated by ML or REML and inverse-variance GLS weights, HKSJ rescales the coefficient covariance by residual dispersion and uses residual degrees of freedom. The modified version floors the covariance multiplier at one.
- Model-based Satterthwaite
Uses the expected information for the covariance parameters to approximate how uncertainty in estimated heterogeneity affects the degrees of freedom of each coefficient or contrast. It requires an identifiable, interior heterogeneity fit. Fixed or boundary estimates do not qualify.
- Cluster-robust inference
Uses a sandwich covariance constructed from independent clusters. Keep all dependent rows in the same cluster. Adjustments include CR2 and CR3. Robust Satterthwaite derives degrees of freedom from cluster contributions, a separate calculation from the model-based method. Use
robust_wald()for joint coefficient hypotheses when the fitted model contains robust inference information.
See mars_inference_options for the model compatibility table, argument combinations, and estimability requirements. Network and repeated-effects models support model normal, model Satterthwaite, and robust inference where eligible. HKSJ and residual-df model t apply to independent univariate fits. In network models, overrides cover basic coefficients and total treatment contrasts. Direct and indirect tests, incoherence diagnostics, rankings, and predictions use their fitted calculations.
Profiling, resampling, and interpretation
- Profile likelihood
Use
profile_likelihood()orprofile_random_effects()to see how the likelihood changes while a parameter is held fixed and other parameters are reoptimized. Profiles can reveal asymmetry, weak identification, or a variance boundary that a Wald interval may obscure.- Bootstrap and jackknife
Bootstrap refits quantify sampling variability under the chosen resampling design. Jackknife refits show how estimates change when independent units are omitted. The range of omitted-fit estimates is a sensitivity summary. Use
mars_alt_estimation()ornetwork_alt_estimation()to run supported refits.- Permutation tests
Use
replicate_permutation()for supported independent univariate null tests. The intercept-only test uses sign changes. Moderator permutation tests a global null and requires exchangeability. Network permutation tests are unsupported.- Confidence, prediction, and multiplicity
A confidence interval for a mean effect quantifies uncertainty in that mean. A prediction interval addresses an effect in a new study and accounts for heterogeneity. See
network_prediction_intervals()for network contrasts. Holm or Bonferroni adjustment of network contrast p-values leaves their confidence intervals pointwise.
Check residual patterns and
influential studies. For dependent effects,
consider how results change under plausible sampling covariance assumptions.
If you use missing = "em" to complete continuous moderators, standard
errors condition on that completion and exclude imputation uncertainty.
Author(s)
Maintainer: Brandon LeBeau lebebr01+mars@gmail.com (ORCID)
Authors:
Brandon LeBeau lebebr01+mars@gmail.com (ORCID)
Ariel M. Aloe amaloe+mars@gmail.com
See Also
Run vignette(package = "mars") to list installed vignettes.
See the package website for worked examples.
Examples
fit <- mars(school, formula = effect ~ 1, studyID = "study",
variance = "var", varcov_type = "univariate",
structure = "univariate")
summary(fit, inference = "model", test = "z")
summary(fit, inference = "model", test = "hksj",
hksj_adjust = "modified")
summary(fit, inference = "robust", cluster = "district",
robust_type = "CR2", test = "Satterthwaite")
Mul R2
Description
Deprecated. Use model_fit() for a model fitted to a single correlation
matrix or path_model() for a model fitted after meta-analytic synthesis.
Usage
Mul_R2(model_input, R)
Arguments
model_input |
Model input as a character string. Multiple models need to be on their own line. Model syntax uses lavann like syntax, see details for more details about this syntax. |
R |
A correlation matrix, most likely this will be the average correlation matrix outputted from the metafor package. |
Value
A vector of names
Compute SMDs after combining disjoint subgroups within arms
Description
Reconstructs each arm's mean and SD, including between-subgroup variation,
and calls compute_es() for two explicitly selected arms. Subgroups must
partition each arm at the same outcome/time without overlapping participants.
Usage
aggregate_es_subgroups(
data,
study_id,
arm_id,
subgroup_id,
mean,
sd,
n,
group1,
group2,
disjoint,
outcome_id = NULL,
time_id = NULL,
source_id = NULL,
correction = c("hedges_exact", "hedges_approx", "none"),
variance_method = c("LS", "J2_LS", "JOINT_DELTA"),
conf_level = 0.95
)
Arguments
data |
Data frame with one row per subgroup within an arm/outcome/time. |
study_id, arm_id, subgroup_id, mean, sd, n |
Column names, quoted or unquoted, for study, arm, subgroup, mean, SD and sample size. Each subgroup requires finite numeric summaries, n an integer greater than 1 and SD nonnegative. |
group1, group2 |
Explicit scalar arm labels; the contrast is group1 minus group2. Each study/outcome/time stratum must contain both selected arms. |
disjoint |
Must be explicitly TRUE. This declares both disjoint subgroups within arms and independent participants across the two selected arms. Overlap cannot be detected from summaries; use another design if present. |
outcome_id, time_id |
Optional column names separating outcome/time strata. Do not omit these if rows describe different outcomes or measurement times. |
source_id |
Optional globally unique source-row ID column; defaults to original row numbers. Supplied IDs preserve traceability across input reorderings. |
correction, variance_method, conf_level |
Passed to |
Details
Let n_j, m_j, and s_j be the sample size, mean, and
standard deviation of subgroup j. The combined sample size, mean,
and variance are
n = \sum_j n_j, \qquad m = \frac{\sum_j n_j m_j}{n},
s^2 = \frac{\sum_j (n_j-1)s_j^2 + \sum_j n_j(m_j-m)^2}{n-1}.
Numeric validation applies to selected arms; unrelated arms are retained in the original data but excluded explicitly. Duplicate subgroup identifiers within a study/arm/outcome/time stratum are rejected.
Value
A mars_es object with original subgroup data in original_data,
aggregation$arms containing reconstructed summaries, and
aggregation$source_map linking source rows to arm and effect IDs.
Unselected-arm rows are listed in aggregation$excluded_source_ids.
effect_data retains one reconstructed comparison per effect for subsequent
compute_es_covariance() calls. Covariance is not inferred by aggregation;
repeated strata require explicit dependence and participant declarations.
References
Higgins, J. P. T., Li, T., and Deeks, J. J. (2019). Choosing effect measures and computing estimates of effect. In Cochrane Handbook for Systematic Reviews of Interventions (2nd ed., pp. 143–176), section 6.5.2.10. Wiley. doi:10.1002/9781119536604.ch6.
Examples
arms <- data.frame(study = 1, arm = rep(c("T", "C"), each = 2),
subgroup = rep(1:2, 2), m = c(12, 14, 10, 11),
s = c(3, 4, 3, 2), n = c(20, 25, 18, 22))
aggregate_es_subgroups(arms, study, arm, subgroup, m, s, n,
"T", "C", disjoint = TRUE)$aggregation$arms
Between-case standardized mean difference for replicated AB designs
Description
Calculates a case-adjusted standardized mean difference for replicated AB single-case data and an approximate sampling variance. The estimator is a small-sample corrected intervention coefficient from a linear model with case fixed effects, divided by its residual standard deviation.
Usage
bc_smd_computation(
data,
studyID,
subjectID,
outcome_name,
phase_name,
phase_order = NULL,
improvement = c("increase", "decrease"),
na_option = "listwise"
)
Arguments
data |
Data frame containing repeated observations. |
studyID, subjectID, outcome_name, phase_name |
Character strings naming the study, case, outcome, and phase columns. |
phase_order |
Character vector giving the baseline and intervention
labels, in that order. If |
improvement |
Whether an increase or decrease in the outcome is beneficial. |
na_option |
Currently only |
Details
This initial implementation supports replicated AB data only: every study must contain at least two cases and every case must contribute baseline and intervention observations. It assumes independent residuals conditional on case and phase. It is not a replacement for a design-specific mixed-model BC-SMD for complex multiple-baseline, reversal, or serially correlated data.
Value
A data frame with one row per study. yi is the Hedges-style
small-sample corrected case-adjusted standardized mean difference and vi
is its delta-method sampling-variance approximation.
Examples
dat <- data.frame(
study = rep("S1", 12), case = rep(c("A", "B"), each = 6),
phase = rep(rep(c("baseline", "intervention"), each = 3), 2),
outcome = c(1, 2, 2, 4, 5, 5, 2, 2, 3, 5, 5, 6)
)
bc_smd_computation(dat, "study", "case", "outcome", "phase")
BCG Vaccine Trial Data
Description
Results from 13 prospective clinical trials comparing tuberculosis rates among participants vaccinated with Bacillus Calmette-Guerin (BCG) and unvaccinated controls. The data are useful for univariate meta-analysis, meta-regression, residual diagnostics, publication-bias examples, and profile-likelihood examples in mars.
Usage
bcg
Format
A data frame with 13 rows and 11 columns:
- trial
Trial identifier.
- author
Study author label.
- year
Publication year.
- tpos
Number of tuberculosis cases in the vaccinated group.
- tneg
Number without tuberculosis in the vaccinated group.
- cpos
Number of tuberculosis cases in the control group.
- cneg
Number without tuberculosis in the control group.
- ablat
Absolute latitude of the study location, in degrees.
- alloc
Treatment-allocation method.
- yi
Log risk-ratio effect-size estimate.
- vi
Sampling variance of
yi.
Source
van Houwelingen, H. C., Arends, L. R., & Stijnen, T. (2002). Advanced methods in meta-analysis: multivariate approach and meta-regression. Statistics in Medicine, 21(4), 589-624. doi:10.1002/sim.1040. The data are also distributed with the mixmeta package.
Examples
bcg
Becker 2009 Correlation Data
Description
Study-level correlations among cognitive anxiety, somatic anxiety, self-confidence, and performance. The data include complete and incomplete correlation matrices and are used throughout mars examples for multivariate correlation synthesis, path modeling, latent factor models, and synthesis reports.
Usage
becker09
Format
A data frame with 10 rows and 9 columns:
- ID
Study identifier.
- N
Study sample size.
- Team
Moderator indicating individual (
I) or team (T) sport context.- Cognitive_Performance
Correlation between cognitive anxiety and performance.
- Somatic_Performance
Correlation between somatic anxiety and performance.
- Selfconfidence_Performance
Correlation between self-confidence and performance.
- Somatic_Cognitive
Correlation between somatic anxiety and cognitive anxiety.
- Selfconfidence_Cognitive
Correlation between self-confidence and cognitive anxiety.
- Selfconfidence_Somatic
Correlation between self-confidence and somatic anxiety.
Source
Becker correlation-synthesis example data included with the package;
see inst/raw_data/Becker09.csv.
References
Becker, B. J. and Aloe, A. M. (2019). Model-Based Meta-Analysis and Related Approaches. In H. Cooper, L. V. Hedges, and J. C. Valentine (Eds.), The Handbook of Research Synthesis and Meta-Analysis (3rd ed., pp. 339-363). Russell Sage Foundation. See this chapter for methodological background.
Examples
becker09
Bootstrap one independent-unit sample
Description
Resamples complete independent study or outer-cluster blocks and refits MARS. Duplicate copies receive fresh study, random-group, and robust-cluster IDs.
Usage
bootstrap_mars(
data,
studyID,
effectID = NULL,
sample_size = NULL,
effectsize_type = NULL,
formula = NULL,
variable_names = NULL,
effectsize_name = NULL,
estimation_method = NULL,
variance = NULL,
varcov_type = NULL,
weights = NULL,
structure = NULL,
intercept = FALSE,
missing = "remove",
optim_method = "L-BFGS-B",
robustID = NULL,
multivariate_covs = NULL,
lasso = FALSE,
lasso_args = list(),
tol = NULL,
...
)
Arguments
data |
Data used for analysis |
studyID |
Character string representing the study ID |
effectID |
Character string representing the effect size ID |
sample_size |
Character string representing the sample size of the studies. |
effectsize_type |
Type of effect size being analyzed |
formula |
The formula used for specifying the fixed and random structure. Used for univariate and multilevel structures. |
variable_names |
Vector of character strings representing the attributes with correlations. The attributes that are correlated should be separated by an underscore. |
effectsize_name |
Character string representing the name of the effect size column in the data. |
estimation_method |
Estimator. NULL uses REML for ordinary models and MLE for LASSO. Explicit LASSO estimation must use MLE. |
variance |
Character string representing the name of the variance of the effect size in the data. |
varcov_type |
Sampling covariance type. NULL uses the formula structure or weighted correlation covariance. Specify the SMD covariance type explicitly. |
weights |
User specified matrix of weights for analysis. |
structure |
Between-study covariance structure. NULL infers univariate or multilevel from formula; effect-size inputs use UN, or multivariate for LASSO. |
intercept |
Whether a model intercept should be specified, default is FALSE meaning no intercept. See details for more information. |
missing |
Whether missing data should be removed, or kept. Default is removing. |
optim_method |
Optimization method that is passed to the optim function. Default is 'L-BFGS-B'. |
robustID |
A character vector specifying the cluster group to use for computing the robust standard errors. |
multivariate_covs |
A one-sided formula to specify the covariates used in a multivariate analysis. |
lasso |
Fit the current mars_lasso() engine in every sample. Summaries describe coefficient and selection stability without inferential intervals. |
lasso_args |
Named controls for mars_lasso(), including lambda_grid, folds, selection, seed, maxit and tol. Cross-validation preprocessing is learned separately within each training fold. |
tol |
NULL retains the fitting engine's default: 1e7 factr for ordinary L-BFGS-B fits, or 1e-7 numerical tolerance for LASSO. Supply a LASSO tolerance here or in lasso_args, once. |
... |
Additional arguments forwarded to mars(), such as tau2 or robust_args. |
Examples
boot_fit <- bootstrap_mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
Bootstrap network meta-analysis
Description
Performs one study-level bootstrap resample and refits network_meta.
All rows from sampled studies are retained together. When a study is sampled
more than once, copied study IDs are relabeled so the replicated blocks are
treated as independent bootstrap studies.
Usage
bootstrap_network_meta(
data,
study_id,
treatment_1,
treatment_2,
effect,
variance,
on_error = c("warn", "stop", "keep"),
...
)
Arguments
data |
A contrast-level network meta-analysis data frame. |
study_id |
Character string naming the study ID column. |
treatment_1 |
Character string naming the first treatment column. |
treatment_2 |
Character string naming the second treatment column. |
effect |
Character string naming the effect-size column. |
variance |
Character string naming the sampling-variance column. |
on_error |
How fitting errors should be handled. |
... |
Additional arguments passed to |
Value
A fitted "nma_mars" object, or an "nma_resample_error"
object when on_error is "warn" or "keep" and fitting
fails.
Examples
nma_dat <- data.frame(
study = c("S1", "S2", "S3", "S4"),
treatment_1 = c("A", "A", "B", "A"),
treatment_2 = c("B", "C", "C", "B"),
effect = c(0.20, 0.35, 0.10, 0.15),
variance = c(0.04, 0.05, 0.04, 0.06)
)
boot_fit <- bootstrap_network_meta(
data = nma_dat,
study_id = "study",
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
effect = "effect",
variance = "variance",
model_type = "wls"
)
Build Implied Correlation Matrices for Observed Path Models
Description
Deprecated. Use model_fit() for a model fitted to a single correlation
matrix or path_model() for a model fitted after meta-analytic synthesis.
Usage
c_mat_ft(model_input, R)
Arguments
model_input |
Model input as a character string. Multiple models need
to be on their own line. Regression syntax uses a lavaan-like
|
R |
A named correlation matrix, typically the pooled correlation matrix
extracted from a fitted |
Details
This helper builds the RAM-style matrices used by observed-variable path
models. Directed paths are stored in A_mat; residual variances and
exogenous covariances are stored in S_mat; and the implied
correlation matrix is computed as
(I - A)^{-1} S (I - A)^{-T}.
Value
A list containing the directed-effects matrix, residual covariance
matrix, implied correlation matrix, multiple-R^2 values, number of
free parameters, and model degrees of freedom.
Confirmatory Factor Analysis After Correlation Synthesis
Description
Fit a confirmatory factor model with matched correlation-structure WLS when sampling covariance is available, or explicitly fit the pooled matrix descriptively.
Usage
cfa_from_synthesis(
mars_object,
model,
num_obs = NULL,
method_null = "sem",
synthesis_method = c("model", "average", "weighted"),
synthesis_transform = c("none", "fisher_z"),
missing_corr = c("available", "pairwise", "em"),
attenuation = c("none", "correct"),
reliability = NULL,
reliability_missing = c("error", "skip", "impute_mean", "assume_1"),
pd_adjust = c("none", "eigen_clip", "nearpd"),
pd_tol = 1e-08,
fit_method = c("auto", "wls", "descriptive"),
se_method = c("delta", "simulation", "bootstrap"),
vcov_source = c("model", "robust"),
se_draws = 1000L,
se_seed = NULL,
...
)
## S3 method for class 'cfa_mars'
print(x, ...)
Arguments
mars_object |
A fitted object returned by |
model |
Lavaan-style latent model syntax. |
num_obs |
Optional size for internal conditional calculations. It does not enable fit tests for synthesized correlations. |
method_null |
Null model method passed to |
synthesis_method |
Correlation synthesis method: |
synthesis_transform |
Optional pooling transform for
|
missing_corr |
Missing-correlation handling for synthesized matrices.
One of |
attenuation |
Attenuation-correction mode for synthesized correlations.
One of |
reliability |
Reliability input used when |
reliability_missing |
Strategy for missing reliability values.
One of |
pd_adjust |
Positive-definite repair for synthesized correlations:
|
pd_tol |
Minimum eigenvalue tolerance used by
|
fit_method |
|
se_method |
|
vcov_source |
Source of pooled-correlation uncertainty. |
se_draws |
Number of draws/resamples used when
|
se_seed |
Optional random seed for |
... |
Additional arguments passed to downstream methods. |
x |
An object of class |
Details
See path_model() for the WLS objective, unit-variance constraints,
expected-information uncertainty, global tests and supported syntax. The
default provides WLS loading SEs when matched uncertainty is available.
Descriptive latent delta SEs and single-sample global fit tests are withheld.
Outputs distinguish marker-scaled raw loadings from standardized loadings;
a raw loading above one is not by itself an inadmissible solution.
Value
A path object with additional class cfa_mars.
Examples
d <- data.frame(ID=1:5,N=200,x2_x1=.56,x3_x1=.42,x4_x1=.63,
x3_x2=.48,x4_x2=.72,x4_x3=.54)
fit <- mars(d,studyID="ID",effectID="numID",sample_size="N",
effectsize_type="cor",varcov_type="weighted",estimation_method="FE",
variable_names=c("x2_x1","x3_x1","x4_x1","x3_x2","x4_x2","x4_x3"))
cfa <- cfa_from_synthesis(fit,"F =~ x1+x2+x3+x4")
cfa$standardized_loadings
cfa$fit_measures$Model
Extract MARS coefficient estimates
Description
Extract MARS coefficient estimates
Usage
## S3 method for class 'mars'
coef(object, ...)
Arguments
object |
A fitted |
... |
Unused. |
Coefficients and Prediction for Penalized MARS Models
Description
Coefficients and Prediction for Penalized MARS Models
Usage
## S3 method for class 'mars_lasso'
coef(object, s = NULL, standardized = FALSE, ...)
## S3 method for class 'mars_lasso'
predict(
object,
newdata = NULL,
s = NULL,
type = c("response", "working", "matrix"),
matrix_action = c("warn", "error", "repair", "none"),
...
)
Arguments
object |
Fitted mars_lasso object. |
s |
NULL for the selected penalty, or an exact fitted lambda value. No interpolation or refitting is performed. |
standardized |
Return coefficients on the optimization scale instead of the original supplied design scale. |
... |
Unsupported arguments are rejected. |
newdata |
Raw predictor records. NULL uses the training data. Correlation matrix prediction needs the internal study and effect columns stored on object. |
type |
response returns effect-scale population predictions; working returns the fitting scale; matrix returns complete named predicted correlation matrices. |
matrix_action |
warn, error, repair or none, as in predict.mars_rf(). Explicit repair records matrix changes; bounded pairs do not ensure joint validity. |
Value
Coefficients as a named numeric vector, or predictions as a vector/list of matrices. Predictions omit BLUPs and do not provide post-selection intervals. A zero coefficient is not a hypothesis-test result. Frozen training transforms and conditional EM moments are used for new records.
Coefficients and covariance of coherent network models
Description
Coefficients and covariance of coherent network models
Usage
## S3 method for class 'nma_coherent'
coef(object, ...)
## S3 method for class 'nma_coherent'
vcov(object, ...)
Arguments
object |
A fitted coherent network model, including repeated-effects fits. |
... |
Reserved; unused arguments are rejected. |
Value
coef() returns named basic treatment effects and moderator coefficients.
vcov() returns their covariance, using the fit's model or CR1 inference.
See Also
confint.nma_coherent(), network_meta_coherent()
Compute summaries from alternative estimation replications
Description
Compute summaries from alternative estimation replications
Usage
compute_alt_stats(
object,
type = NULL,
quantiles = c(0.025, 0.5, 0.975),
level = 0.95,
original_fit = NULL
)
Arguments
object |
A list of fitted replication models from bootstrap, jackknife, or permutation. |
type |
Type of alternative estimation summary to compute. |
quantiles |
Quantiles for descriptive replicate-distribution summaries. |
level |
Coverage for bootstrap percentile CIs, jackknife model-fit CIs, and descriptive jackknife ranges, independent of the displayed quantiles. |
original_fit |
Optional original full-data fit; normally retained by the replicate wrapper. |
Details
Bootstrap draws are retained in boot_repl; quantiles
contains empirical percentiles and bootstrap_se is the sample standard
deviation of each quantity's finite draws. Bootstrap CIs are percentile intervals.
Bootstrap SEs and intervals require at least two finite estimates
and an 80 percent per-term success rate; these are minimum computation guards,
not calibration guarantees. Coefficient identities are preserved; other
quantities use stable statistic. keys to prevent collisions across omissions.
Jackknife summaries report the original estimate, omission minima/maxima,
descriptive sensitivity quantiles, and maximum absolute changes from the
original fit. omission_changes retains signed changes indexed by omitted
unit. jackknife_comparisons contains each omitted fit's estimates,
SEs, CIs, and signed changes from the original inference.
jackknife_uncertainty summarizes SE ranges and maximum changes in
SEs and confidence limits. Model-based and cluster-robust inference are
labelled separately, with robust degrees of freedom retained. These compare
the inference from fitted models without computing another sampling SE from
the omission distribution. complete and n_valid
identify incomplete omission sequences; ranges describe the available fits.
type defaults to retained method metadata; supply it for manually assembled lists.
LASSO summaries report descriptive quantiles and nonzero-coefficient frequencies
for penalized terms; unpenalized baselines have no selection frequency. They
do not report confidence intervals or jackknife standard errors.
Multivariate heterogeneity includes outcome-labelled variances and covariances.
Examples
boot_reps <- replicate_bootstrap(
number_bootstraps = 5,
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
compute_alt_stats(boot_reps, type = "bootstrap")
Compute effect sizes from reported study statistics
Description
Computes continuous, correlation, binary, proportion and ratio effect sizes
from explicitly selected reported statistics. This release supports only the routes listed
by es_methods(). No automatic selection among competing statistics occurs.
Usage
compute_es(
data,
measure = "SMD",
design,
input,
m1 = NULL,
sd1 = NULL,
n1 = NULL,
m2 = NULL,
sd2 = NULL,
n2 = NULL,
t = NULL,
f = NULL,
df = NULL,
df1 = NULL,
p = NULL,
effect_sign = NULL,
correction = c("hedges_exact", "hedges_approx", "none"),
variance_method = c("LS", "J2_LS"),
conf_level = 0.95,
study_id = NULL,
effect_id = NULL,
errors = c("collect", "stop"),
se1 = NULL,
se2 = NULL,
se_type = NULL,
lower1 = NULL,
upper1 = NULL,
lower2 = NULL,
upper2 = NULL,
ci_level1 = NULL,
ci_level2 = NULL,
ci_method = NULL,
ci_tolerance = 1e-08,
sd_total = NULL,
total_sd_scope = NULL,
reference_group = NULL,
r = NULL,
n_total = NULL,
predictors = NULL,
r_squared = NULL,
events1 = NULL,
non_events1 = NULL,
events2 = NULL,
non_events2 = NULL,
events = NULL,
person_time1 = NULL,
person_time2 = NULL,
zero_cell = NULL,
estimate = NULL,
estimate_se = NULL,
adjustment = NULL,
r_digits = NULL,
r_squared_digits = NULL
)
## S3 method for class 'mars_es'
print(x, ...)
## S3 method for class 'mars_es'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)
Arguments
data |
A data frame. Its row order is preserved; the original data are
retained separately in |
measure |
Target measure: |
design |
Required design: independent_groups for group contrasts, independent_observations for COR/ZCOR, ordinary_regression for partial/ semipartial correlations, single_group for proportions, survival for HR. May identify a data column; unsupported designs receive diagnostics. |
input |
Required route: |
m1, sd1, n1, m2, sd2, n2 |
Group means, SDs and sample sizes, with group 1 minus
group 2 defining the effect direction. Supply unquoted/quoted column names,
numeric vectors of length |
t |
Signed pooled Student t for input=student_t, or ordinary OLS focal coefficient t for input=regression_t. Welch, paired, robust and clustered tests are ineligible; only regression_t allows covariate adjustment. |
f |
Nonnegative F statistic from a two-group unadjusted one-way ANOVA. |
df |
Residual degrees of freedom for test-statistic routes. Must equal
|
df1 |
Numerator degrees of freedom for F, which must equal 1. |
p |
Exact two-sided p-value from the eligible Student t test, in |
effect_sign |
Direction ( |
correction |
|
variance_method |
|
conf_level |
Confidence level for normal-approximation Wald intervals. |
study_id |
Optional study identifiers. These do not assert independence between multiple effects sharing a study. |
effect_id |
Optional unique, nonmissing effect identifiers. Defaults to sequential row identifiers. |
errors |
|
se1, se2 |
SEs of individual arm means for |
se_type |
Required for |
lower1, upper1, lower2, upper2 |
Confidence limits for the individual arm means. |
ci_level1, ci_level2 |
Reported arm-mean confidence levels, each strictly
between zero and one. These are distinct from the output |
ci_method |
Required for |
ci_tolerance |
Allowed midpoint error as a fraction of the interval's half-width (default 1e-8), plus machine-roundoff allowance. Set explicitly for rounded reports; must be in [0,1). The reported mean is never replaced. |
sd_total |
Sample SD across both groups combined, including between-group variation. This is not the within-group pooled SD. |
total_sd_scope |
Required for |
reference_group |
Required for GLASS: numeric 1 or 2, identifying the arm whose SD defines the standardizer. May be a column or row-specific vector. This choice does not change the group1-minus-group2 numerator. |
r |
Reported Pearson, partial or semipartial correlation, according to measure. Fisher transformation is selected through the Z-prefixed measure. |
n_total |
Total observation count for correlations or single proportions. |
predictors |
Total regression slopes, including the focal predictor and
controls, excluding the intercept. Must be an integer >= 1. Residual df is
|
r_squared |
Full-model, unadjusted R-squared in [0,1), required for
semipartial correlations and their variances. It must be at least |
events1, non_events1, events2, non_events2 |
Nonnegative integer binomial cells. Each arm must have a positive total. Ratios contrast group 1 with group 2. events1/events2 also supply incidence counts for IRR. |
events |
Nonnegative integer events for a single proportion. |
person_time1, person_time2 |
Positive exposures in comparable units for independent Poisson incidence counts; required for IRR. |
zero_cell |
Required for count routes: none or add_half. add_half adds 0.5 to all four binomial cells if any is zero, both proportion cells at a boundary, or both incidence counts if one is zero (exposure unchanged). RD and PR require none. Both-zero event comparisons remain unavailable for ratios; OR also excludes both-all-event comparisons. No rows are dropped. |
estimate, estimate_se |
Reported log hazard ratio and its positive SE on the log scale. A raw HR must first be logged; its raw-scale SE is ineligible. |
adjustment |
Required for HR: adjusted or unadjusted. The original data should retain the adjustment variables and model details for comparability. |
r_digits, r_squared_digits |
Optional decimal reporting precision (integer 0 through 15) for directly reported semipartial r and R-squared. Nearest- rounding intervals distinguish contradictory inputs from rounding ambiguity. Compatible but inconsistent reported points receive rounding_ambiguous: the point is retained but variance is withheld; no value is clipped or replaced. |
x |
A |
... |
Additional arguments passed to the data-frame print method. |
row.names, optional |
Passed to the data-frame conversion method. |
Details
Provenance includes variance_formula and variance_basis. Small effective samples (<30) and sparse cells (<5) generate inference notes as screening heuristics, not validated pass/fail cutoffs. Semipartial results always note their distinct random-X sampling assumptions. These notes do not improve interval coverage or justify filtering studies with unavailable variances.
transform_es() provides explicit first-order delta propagation, including
full supplied covariance matrices. The original results are preserved.
The exact Hedges correction is
J=\Gamma(\nu/2)/(\sqrt{\nu/2}\Gamma((\nu-1)/2)),
with \nu=n_1+n_2-2. Its approximation is 1-3/(4\nu-1).
y_i=Jd, with J=1 for Cohen's d. Normality and common population variance
underlie this correction's usual unbiasedness interpretation. An exact bias
correction does not make the variance or confidence interval exact.
For GLASS let r denote the reference arm and o the other arm.
Here \nu=n_r-1 and d=(m_1-m_2)/s_r. HET uses
v=(s_o/s_r)^2/(n_o-1)+1/(n_r-1)+y_i^2/[2(n_r-1)].
LS uses 1/n_1+1/n_2+y_i^2/(2n_r); J2_LS uses
J^2[1/n_1+1/n_2+d^2/(2n_r)]. These are named approximations, matching
metafor SMD1H and SMD1 LS/LS2 respectively; HET permits unequal variances.
At reference df <= 1 corrected GLASS is unavailable (raw d retained);
at reference df <= 2 no GLASS variance or interval is returned.
All output intervals use normal Wald quantiles, including MD; they are not
Welch-t or exact intervals. Zero estimated MD variance is diagnosed rather
than supplied as a usable inverse-variance weight. MD's d and df are NA.
For JOINT_DELTA, let q=\sum_i w_i s_i^2. SMD uses
w_i=(n_i-1)/(n_1+n_2-2); GLASS puts weight 1 on the reference arm.
With y_i=J(m_1-m_2)/\sqrt{q}, the implemented variance is
v=J^2(s_1^2/n_1+s_2^2/n_2)/q
+y_i^2\sum_h w_h^2 s_h^4/(n_h-1)/(2q^2).
This plug-in first-order approximation treats the sample sizes and correction J as fixed and accounts for uncertainty in the standardizer. It assumes independent normal arms and does not require equal observed SDs. It differs from LS, J2_LS and HET and is never selected automatically. Full formulas are installed in compute-es/COVARIANCE.md. Per-row correction and variance choices are recorded in data and provenance; settings records the call-level choices and whether defaults were used.
COR uses v=(1-r^2)^2/(n-1), and ZCOR uses 1/(n-3).
With k total slopes, PCOR uses (1-r^2)^2/(n-k) and ZPCOR uses
1/(n-k-2). SPCOR uses the variance
v=[(1-R^2)^2+(R^2-r^2)(1-R^2+r^2)]/n.
ZSPCOR divides this variance by (1-r^2)^2.
Fisher z is not variance stabilizing for semipartial correlations. Regression
t reconstruction requires ordinary OLS with an intercept, not robust,
clustered, weighted or generalized-model t statistics.
OR, RR, IRR, ROM and HR return log-scale yi/vi. PR, PLO and PLN use raw, logit and log probability scales respectively. See display for transformed interpretation; analyze data$yi with data$vi, never pair display estimates with analysis-scale variances. Wald limits on bounded raw scales are not clipped and can exceed the parameter bounds. Sparse-data approximations can be poor; zero estimated variance is diagnosed, not used as infinite precision. The full formulas, assumptions and boundary policies are installed in compute-es/FAMILIES.md. These routes do not establish complete Appendix B coverage, and do not estimate cross-effect sampling covariance.
This interface does not pool estimates or convert paired/adjusted effects to unadjusted SMDs. Inspect diagnostics before selecting rows for analysis. Other supplied statistics are preserved but do not override the explicitly chosen route. No dependency on metafor is required for computation.
Value
A mars_es list with data (one result row per input row),
original_data, normalized inputs, provenance, assumptions,
reconstruction (recovered SEs/SDs and numerical notes), diagnostics, the formula
display (back-transformed estimates/limits, scale labels and separate
display diagnostics; no transformed variances), inference_notes (cautions
that do not exclude rows or change their analysis status),
registry, settings, and sampling_covariance = NULL. NULL means that
cross-effect covariance was not computed, not that it is zero.
References
Hedges, L. V. (1981). Distribution theory for Glass's estimator of effect size and related estimators. Journal of Educational Statistics, 6, 107-128. doi:10.3102/10769986006002107.
Lipsey, M. W. and Wilson, D. B. (2001). Practical Meta-Analysis. Sage. Appendix B. This release implements selected route families, not the complete appendix.
Aloe, A. M., and Becker, B. J. (2012). An Effect Size for Regression Predictors in Meta-Analysis. Journal of Educational and Behavioral Statistics, 37(2), 278–297. doi:10.3102/1076998610396901.
Aloe, A. M., and Thompson, C. G. (2013). The Synthesis of Partial Effect Sizes. Journal of the Society for Social Work and Research, 4(4), 390–405. doi:10.5243/jsswr.2013.24.
Aloe, A. M. (2014). An Empirical Investigation of Partial Effect Sizes in Meta-Analysis of Correlational Data. The Journal of General Psychology, 141(1), 47–64. doi:10.1080/00221309.2013.853021.
Hedges, L. V., Gurevitch, J., and Curtis, P. S. (1999). The Meta-Analysis of Response Ratios in Experimental Ecology. Ecology, 80(4), 1150–1156. doi:10.1890/0012-9658(1999)080[1150:TMAORR]2.0.CO;2.
Lajeunesse, M. J. (2011). On the Meta-Analysis of Response Ratios for Studies with Correlated and Multi-Group Designs. Ecology, 92(11), 2049–2055. doi:10.1890/11-0423.1.
Examples
dat <- data.frame(mt=12, st=3, nt=30, mc=10, sc=3, nc=30)
es <- compute_es(dat, design="independent_groups", input="means_sd",
m1=mt, sd1=st, n1=nt, m2=mc, sd2=sc, n2=nc)
es$data
es_methods()
Construct sampling covariance for dependent effect sizes
Description
Attaches a named sampling covariance matrix to compute_es() results using
explicit participant, measurement and variable identities. Supports MD, ROM,
OR, RR, RD, IRR, PR, PLO, PLN, SMD, GLASS, COR and ZCOR. One measure per call.
Usage
compute_es_covariance(
x,
study_id,
arm1 = NULL,
arm2 = NULL,
outcome_id = NULL,
time_id = NULL,
independent_arms = FALSE,
independent_studies = FALSE,
dependence = NULL,
same_participants = FALSE,
variable1 = NULL,
variable2 = NULL,
correlation_matrices = NULL,
common_sample = FALSE
)
Arguments
x |
An untransformed |
study_id, arm1, arm2, outcome_id, time_id |
Column names in |
independent_arms |
Explicit TRUE for arm methods: distinct arm IDs in a study identify disjoint independent participant sets. |
independent_studies |
Explicit TRUE: distinct studies are independent. |
dependence |
Optional data frame with columns |
same_participants |
Explicit TRUE for multiple outcomes/times within an arm: the same complete participant set supplies both measurements. Binary and continuous sample sizes must agree. Partial overlap is unsupported. |
variable1, variable2 |
Variable identities for COR/ZCOR, resolved like study_id. Distinct variables are required within each reported correlation. |
correlation_matrices |
Named list (one matrix per study) of complete, named, symmetric, positive-semidefinite Pearson correlation matrices for COR/ZCOR. Reported correlations must match the corresponding matrix entries. |
common_sample |
Explicit TRUE for COR/ZCOR: every correlation in each study uses the same complete sample. Sample sizes must agree and be >= 5. |
Details
See the installed compute-es/COVARIANCE.md for full formulas, definitions,
worked examples, assumptions and limitations. The following are plug-in
formulas; nonlinear transformations use first-order approximations.
Shared arms at one outcome/time retain the original method:
V=A\,\mathrm{diag}(q)\,A^T,
with signed contrast matrix A and arm contribution variances
MD: s^2/n; ROM: s^2/(nm^2); OR: 1/a+1/b;
RR: 1/a-1/n; RD: p(1-p)/n; IRR: 1/a.
Here a and b count events and non-events, n=a+b, and p=a/n.
For repeated binary outcomes j and k on n participants, let a_{jk} count joint
events. Then B_{jk}=(a_{jk}/n-p_j p_k)/n.
Transform with derivatives 1 (PR/RD), 1/p (PLN/RR), or
1/[p(1-p)] (PLO/OR), and the contrast signs: V=D B D^T.
For IRR, B is the supplied count covariance with Poisson diagonal a,
and the signed log-count derivatives are 1/a. Fixed exposures affect
point estimates but not these derivatives. Joint-event counts alone do not
identify recurrent-event count covariance.
Under independent multivariate-normal observations within an arm,
\mathrm{Cov}(\bar X_j,\bar X_k)=r_{jk}s_js_k/n,
\mathrm{Cov}(s_j^2,s_k^2)=2r_{jk}^2s_j^2s_k^2/(n-1).
Mean/sample-variance cross covariances are zero under normality. For SMD/GLASS
write y=J\Delta/\sqrt{q}, q=\sum_h w_h s_h^2.
SMD uses w_h=(n_h-1)/(n_1+n_2-2); GLASS puts weight 1 on the
declared reference arm. Mean derivatives are signed J/\sqrt{q};
sample-variance derivatives are -y w_h/(2q). Use
variance_method="JOINT_DELTA" in compute_es for SMD/GLASS. Existing LS,
J2_LS and HET marginals are not silently rescaled or replaced.
For Pearson correlations r_{ab} and r_{cd}, define
K_{ab,cd}=r_{ac}r_{bd}+r_{ad}r_{bc}
-r_{ab}(r_{ac}r_{ad}+r_{bc}r_{bd})
-r_{cd}(r_{ac}r_{bc}+r_{ad}r_{bd})
+\tfrac12 r_{ab}r_{cd}(r_{ac}^2+r_{ad}^2+r_{bc}^2+r_{bd}^2).
COR uses K/(n-1). ZCOR uses
K/[(n-3)(1-r_{ab}^2)(1-r_{cd}^2)], matching the specialized
Fisher marginal variance. Delta-transforming COR instead retains n-1.
All joint matrices must be positive semidefinite; binary joint counts also obey the feasible two-by-two table bounds. Pairwise feasibility and PSD are necessary but not sufficient for a joint Bernoulli distribution with three or more outcomes. Use joint counts from coherent participant-level data. Covariance diagonals must match the source variances. No matrix repair, automatic independence, overlap approximation or continuity correction of joint counts is performed. Redundant contrasts may produce singular V; choose a nonredundant set for fitting functions requiring invertible V.
Value
The original result with sampling_covariance, covariance_blocks
and covariance_provenance. Estimates and marginal variances are preserved.
Provenance includes identities, formulas, supplied dependence, and (for
joint arm methods) the primitive covariance and Jacobian used to form V.
Continuous joint calculations use standardized summary fluctuations to
avoid overflow/underflow. primitive_coordinates and primitive_sd_scales
record these coordinates; the reported Jacobian uses the same coordinates,
so its product with primitive_covariance reconstructs V.
References
Steiger, J. H. (1980). Tests for comparing elements of a correlation matrix. Psychological Bulletin, 87, 245-251. doi:10.1037/0033-2909.87.2.245.
Oehlert, G. W. (1992). A note on the delta method. The American Statistician, 46(1), 27–29. doi:10.1080/00031305.1992.10475842.
Examples
dat <- data.frame(a=c("T1","T2"), b="C", m1=c(12,13), m2=10,
sd1=3, sd2=2, n1=30, n2=25)
es <- compute_es(dat, measure="SMD", design="independent_groups",
input="means_sd", m1=m1, m2=m2, sd1=sd1, sd2=sd2, n1=n1, n2=n2,
variance_method="JOINT_DELTA")
es <- compute_es_covariance(es, study_id="s1", arm1=a, arm2=b,
outcome_id="score", time_id="post", independent_arms=TRUE,
independent_studies=TRUE)
es$sampling_covariance
Compute summaries from network meta-analysis resampling replications
Description
Compute summaries from network meta-analysis resampling replications
Usage
compute_network_alt_stats(
object,
type = NULL,
quantiles = c(0.025, 0.5, 0.975),
level = 0.95,
original_fit = NULL
)
## S3 method for class 'nma_resamples'
summary(
object,
type = NULL,
quantiles = c(0.025, 0.5, 0.975),
level = 0.95,
digits = 4,
...
)
## S3 method for class 'nma_boot'
summary(object, digits = 4, ...)
## S3 method for class 'nma_boot'
print(
x,
...,
digits = if (is.null(attr(x, "display_digits"))) 4 else attr(x, "display_digits")
)
Arguments
object |
A list of fitted |
type |
Type of alternative estimation summary to compute. |
quantiles |
Quantiles for distribution summaries. |
level |
Coverage for bootstrap percentile CIs, jackknife model-fit CIs, and descriptive jackknife ranges. |
original_fit |
Optional original full-data network fit. |
digits |
Decimal places for network resampling output, from 1 to 22. |
... |
Additional arguments passed to compute_network_alt_stats(). |
x |
A computed network resampling summary. |
Details
Summaries retain treatment, outcome, and time identities. Full-data
reference selection is retained by replicate wrappers. Fits losing treatments
are recorded as failed rather than changing the estimand. Moderator coefficients
retain their treatment, moderator, outcome, and time coordinates across fits.
Bootstrap boot_repl contains the empirical draws; quantiles gives
their percentiles and bootstrap_se is their sample standard deviation.
Bootstrap SEs and CIs require at least two finite draws and an 80 percent
per-quantity success rate. Jackknife summaries describe changes from the
original fit, omission minima/maxima, and maximum absolute changes.
jackknife_comparisons retains each omitted fit's estimates, SEs, CIs,
and signed changes from full-data inference. jackknife_uncertainty
summarizes SE ranges and maximum changes in SEs and confidence limits.
These use the inference from each fitted model, including its degrees of
freedom, without computing another SE from the omission distribution.
omission_changes retains signed changes
indexed by omitted study. Inspect complete and n_valid for
incomplete omissions; the reported ranges describe available fits only.
Value
An "nma_boot" object containing replicate estimates,
quantiles, bootstrap uncertainty or jackknife sensitivity summaries, and
a separate moderator_summary table when moderators are fitted.
Examples
nma_dat <- data.frame(
study = c("S1", "S2", "S3", "S4"),
treatment_1 = c("A", "A", "B", "A"),
treatment_2 = c("B", "C", "C", "B"),
effect = c(0.20, 0.35, 0.10, 0.15),
variance = c(0.04, 0.05, 0.04, 0.06)
)
nma_reps <- replicate_network_bootstrap(
number_bootstraps = 2,
data = nma_dat,
study_id = "study",
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
effect = "effect",
variance = "variance",
model_type = "wls"
)
compute_network_alt_stats(nma_reps)
Deprecated permutation wrapper
Description
Use replicate_permutation() for the same arguments and results.
Usage
conduct_permutation(number_permutations = 999, future_seed = TRUE, ...)
Arguments
number_permutations |
The number of permutations to perform, default is 999. |
future_seed |
Seed control forwarded to |
... |
Additional arguments passed to |
Value
The result of replicate_permutation().
Confidence intervals for MARS coefficients
Description
Confidence intervals for MARS coefficients
Usage
## S3 method for class 'mars'
confint(
object,
parm,
level = 0.95,
type = c("model", "robust"),
method = c("wald", "profile"),
vcov_method = NULL,
inference = NULL,
test = NULL,
robust_type = NULL,
hksj_adjust = NULL,
cluster = NULL,
...
)
Arguments
object |
A fitted |
parm |
Coefficients to include. The default includes all coefficients. |
level |
Confidence level. |
type |
Either |
method |
|
vcov_method |
Optional |
inference |
NULL preserves the usual summary; |
test |
NULL uses normal model inference or the stored robust test.
Options are |
robust_type |
Optional robust covariance, such as |
hksj_adjust |
|
cluster |
Optional column name in the fitted analysis data identifying independent robust clusters. Defaults to the stored robust clustering column. |
... |
For profile intervals, arguments to |
Confidence intervals for coherent network models
Description
Confidence intervals for coherent network models
Usage
## S3 method for class 'nma_coherent'
confint(
object,
parm,
level = 0.95,
type = c("coefficients", "contrasts"),
adjust = c("none", "bonferroni"),
inference = NULL,
test = NULL,
robust_type = NULL,
cluster = NULL,
hksj_adjust = NULL,
...
)
Arguments
object |
A fitted coherent network model. |
parm |
Coefficient names or indices for |
level |
Confidence level strictly between zero and one. |
type |
|
adjust |
|
inference |
Optional summary-only |
test |
Optional summary-only coefficient/total-contrast test: |
robust_type |
Optional summary-only sandwich covariance, e.g. CR2. |
cluster |
Optional fitted contrast-data cluster column, default study_id. |
hksj_adjust |
Unsupported for networks; supplied values raise an error. |
... |
Reserved; unused arguments are rejected. |
Details
Intervals condition on fitted heterogeneity. Model inference uses normal quantiles; CR1 uses a t reference with number of studies minus one df. Interval adjustment is explicit and independent of the fit's p-value adjustment. Holm-adjusted p-values do not imply Holm-adjusted confidence intervals.
Value
For coefficients, a two-column matrix with coefficient row names. For contrasts, a data frame with treatments, outcome/time strata, estimate, standard error, df, lower and upper limits, and family metadata attributes.
References
Higgins, J. P. T., Jackson, D., Barrett, J. K., Lu, G., Ades, A. E., and White, I. R. (2012). Consistency and inconsistency in network meta-analysis: concepts and models for multi-arm studies. Research Synthesis Methods, 3, 98–110. doi:10.1002/jrsm.1044.
White, I. R., Barrett, J. K., Jackson, D., and Higgins, J. P. T. (2012). Consistency and inconsistency in network meta-analysis: model estimation using multivariate meta-regression. Research Synthesis Methods, 3, 111–125. doi:10.1002/jrsm.1045.
See Also
network_meta(), predict.nma_coherent()
Examples
d <- data.frame(s=1:6,a=rep(c("A","A","B"),2),
b=rep(c("B","C","C"),2),g=c(.2,.5,.3,.3,.6,.2),v=.04)
fit <- network_meta(d,"s","a","b","g","v",adjust="holm")
confint(fit)
confint(fit,type="contrasts",level=.90,adjust="bonferroni")
Convert a Mixed Correlation Object to a mars-Compatible Object
Description
Convert a Mixed Correlation Object to a mars-Compatible Object
Usage
corr_to_mars(x)
Arguments
x |
An object returned by |
Value
A list object with the fields required by path_model.
Examples
mixed_out <- mixed_corr_meta(
data = teacher_expectancy,
outcome = "yi",
variance = "vi",
moderators = c("year", "weeks", "setting", "tester"),
bootstrap = 20,
seed = 123
)
mars_like <- corr_to_mars(mixed_out)
names(mars_like)
Helper function to read in data
Description
This function builds a list of correlation matrices from data that are in flat files where a correlation matrix is coded into a single row, a common format for coding correlation matrices.
Usage
df_to_corr(data, variables, ID = NULL)
Arguments
data |
Data frame input used to convert to correlation matrices. |
variables |
A character vector of variable names representing the columns to convert to a pairwise correlation matrix. Variable names take the following format: "columnname_rowname" where the name prior to the underscore is the column name and the name after the underscore is the row name. |
ID |
A variable name, as a character string, to use as names for the list elements. |
Details
Each supplied pair name is mapped to its actual matrix coordinates;
column order does not change pair identity. Supply every distinct pair once,
with values in [-1,1] or NA. Variable names must not contain underscores;
exactly one underscore separates the two variable names. Missing entries are
retained for downstream synthesis. An ID column is optional and supplies list
names; correlation synthesis itself requires independent, distinct study IDs.
Value
A list of correlation matrices.
Examples
becker09 <- read.csv(paste0(system.file('raw_data', package = 'mars'),
'/Becker09.csv'))
becker09_list <- df_to_corr(becker09,
variables = c('Cognitive_Performance',
'Somatic_Performance',
'Selfconfidence_Performance',
'Somatic_Cognitive',
'Selfconfidence_Cognitive',
'Selfconfidence_Somatic'),
ID = 'ID')
Prepare paired diagnostic effects and sampling covariance
Description
Compute logit sensitivity and specificity for two tests applied to the same participants, with one threshold per test.
Usage
dta_paired_effects(
data,
studyID = "study_id",
stratum = "stratum",
pp = "pp",
pn = "pn",
np = "np",
nn = "nn",
tests = c("test1", "test2"),
zero_cell = c("none", "add_half")
)
Arguments
data |
Data frame with two rows per study, one for each reference-standard stratum. |
studyID, stratum |
Names of the study identifier and stratum columns.
Strata must be labeled |
pp, pn, np, nn |
Names of the joint count columns. The letters indicate
positive ( |
tests |
Two distinct test labels, in the order used by the count columns. |
zero_cell |
Use |
Details
Both tests and the reference standard must be observed for the participants represented in the counts. Sensitivity uses positive results in the diseased stratum. Specificity uses negative results in the non-diseased stratum.
The covariance uses a multinomial delta approximation within each stratum. For each test, the logit is the log success count minus the log failure count. Its derivative with respect to a joint cell count is the reciprocal success count for a success cell and the negative reciprocal failure count for a failure cell. The cross-stratum sampling covariances are zero, conditional on the stratum totals. Exact singularities, for example when the tests always agree in a stratum, are retained.
Value
A list with effects, a data frame with four rows per study
containing test and endpoint labels, raw marginal counts, correction
flags, logits (yi), and variances (vi); sampling_covariance,
a named list of 4-by-4 matrices with dimensions labeled by effect_id;
joint_counts, the raw joint tables with the amount added per cell
(added); and zero_cell, the selected correction policy. The effects
and covariance matrices use the order sensitivity then specificity for
test 1, followed by sensitivity then specificity for test 2. Study order
follows first appearance in data. Use study_id and effect_id
together to identify an effect across studies.
References
Nikoloulopoulos, A. K. (2024). Joint meta-analysis of two diagnostic tests accounting for within and between studies dependence. Statistical Methods in Medical Research. doi:10.1177/09622802241269645
See Also
mars_dta_paired(), compute_es_covariance()
Examples
joint <- data.frame(study_id = "s1", stratum = c("diseased", "non_diseased"),
pp = c(20, 4), pn = c(8, 6), np = c(7, 9), nn = c(5, 31))
dta_paired_effects(joint)$sampling_covariance
Evaluate the joint multinomial likelihood for paired diagnostic tests
Description
Evaluate the likelihood of the four joint test outcomes within each reference-standard stratum.
Usage
dta_paired_loglik(joint_counts, probabilities)
Arguments
joint_counts |
A data frame such as the |
probabilities |
A data frame with the same study, stratum, and cell
columns. Each study and stratum must match exactly one count row.
The four joint probabilities must be in |
Details
Conditional on the reference-standard totals, the likelihood is the
product of the two multinomial probabilities in each study. It includes
the multinomial coefficients and uses the raw counts. Any continuity
correction metadata is ignored. Empty cells are valid. A positive count
with zero probability gives a log likelihood of -Inf.
Value
A list with the total log_likelihood and a by_study data
frame with the diseased and non_diseased log contributions and
their sum (log_likelihood). Study order follows first appearance
in joint_counts.
References
Nikoloulopoulos, A. K. (2024). Joint meta-analysis of two diagnostic tests accounting for within and between studies dependence. Statistical Methods in Medical Research. doi:10.1177/09622802241269645
See Also
dta_paired_effects(), dta_threshold_loglik()
Summary ROC curve for diagnostic accuracy models
Description
Calculate a Rutter–Gatsonis summary ROC curve from a Gaussian or binomial
mars_dta() fit.
Usage
dta_sroc(object, newdata = NULL, fpr = seq(0, 1, length.out = 101L))
Arguments
object |
A fitted |
newdata |
Data frame with one row per moderator profile. Required when the fit includes moderators. All moderators, including a measured threshold if supplied in the model, are held fixed within each curve. |
fpr |
Numeric vector of false-positive rates (one minus specificity), between zero and one inclusive. |
Details
The curve varies the latent threshold at the profile's mean accuracy in the Rutter–Gatsonis parameterization. Its logit-scale equation is
\operatorname{logit}(\mathrm{sensitivity}) = \mu_{\mathrm{se}} +
b[\operatorname{logit}(\mathrm{FPR}) + \mu_{\mathrm{sp}}],
where \mu_{\mathrm{se}} and \mu_{\mathrm{sp}}
are the fitted mean logits of sensitivity and specificity, and b is
the slope.
The slope is the ratio of the between-study standard deviations for
logit sensitivity and logit specificity. Each curve is increasing and
passes through its profile's pooled operating point. Profiles share a
slope because mars_dta() estimates a common between-study covariance.
Both between-study variances must exceed 1e-8 times the maximum of one
and the two variances. The curve uses the marginal variances and is also
defined for structure = "DIAG1". The between-study correlation still
enters the joint regions in the ROC plot.
The curve summarizes the fitted model at fixed accuracy. To examine the
association with a measured threshold, use predict.mars_dta() to compare
pooled operating points at different threshold values. False-positive
rates beyond the observed range are extrapolations.
Value
A data frame with columns profile (row of newdata, or 1 for
an intercept-only fit without newdata), fpr, and sensitivity.
The false-positive rates are returned in input order for each profile.
References
Rutter, C. M., and Gatsonis, C. A. (2001). A hierarchical regression approach to meta-analysis of diagnostic test accuracy evaluations. Statistics in Medicine, 20(19), 2865–2884. doi:10.1002/sim.942
Arends, L. R., et al. (2008). Bivariate random effects meta-analysis of ROC curves. Medical Decision Making, 28(5), 621–638. doi:10.1177/0272989X08319957
Harbord, R. M., Deeks, J. J., Egger, M., Whiting, P., and Sterne, J. A. C. (2007). A unification of models for meta-analysis of diagnostic accuracy studies. Biostatistics, 8(2), 239–251. doi:10.1093/biostatistics/kxl004.
See Also
plot.mars_dta(), predict.mars_dta()
Examples
counts <- data.frame(study = 1:8, TP = c(44, 50, 56, 59, 64, 68, 69, 71),
TN = c(52, 42, 62, 74, 53, 65, 59, 72))
counts <- transform(counts, FN = 80 - TP, FP = 90 - TN)
fit <- mars_dta(counts, studyID = "study")
dta_sroc(fit, fpr = c(.1, .2, .5))
Prepare diagnostic effects at multiple thresholds
Description
Compute logit sensitivity and specificity and their sampling covariance for one test measured at nested cutoffs on the same participants.
Usage
dta_threshold_effects(
data,
studyID = "study_id",
threshold = "threshold",
tp = "TP",
fn = "FN",
fp = "FP",
tn = "TN",
positive = c("higher", "lower"),
zero_cell = c("none", "add_half")
)
Arguments
data |
Data frame with one row per study and reported cutoff. Both reference-standard strata must be represented at each cutoff. |
studyID, threshold |
Names of the study identifier and numeric cutoff columns. Use comparable cutoffs on the same scale across studies. |
tp, fn, fp, tn |
Names of the true-positive, false-negative, false-positive, and true-negative count columns. Counts must be finite nonnegative integers, with constant positive stratum totals across cutoffs within each study. |
positive |
Use |
zero_cell |
Use |
Details
Sort each study's cutoffs and reconstruct disjoint score bins by differencing cumulative counts. Each logit is a function of these multinomial bin counts. A joint delta approximation accounts for the overlap between cutoffs within a stratum. Cross-stratum covariances are zero conditional on the stratum totals. Empty bins alone do not trigger a correction, and singular covariance blocks are retained. A correction applies to the whole stratum, including cutoffs whose logits were already finite.
Value
A list containing effects with raw marginal counts, logits
(yi) and sampling variances (vi), sampling_covariance with one
labeled matrix per study, score_bins with raw counts and per-bin
adjustments in increasing score order, and cutoffs with the
threshold and endpoint corresponding to each effect label. The
list also records the positivity direction and correction policy.
For "higher", bins include their lower cutoff. For "lower",
bins include their upper cutoff.
Studies follow first appearance in data. Within each study,
effects and covariance blocks are ordered by ascending cutoff,
sensitivity then specificity.
See Also
Examples
counts <- data.frame(study_id = "s1", threshold = 1:2,
TP = c(40, 30), FN = c(10, 20),
FP = c(30, 10), TN = c(70, 90))
prepared <- dta_threshold_effects(counts)
prepared$score_bins
Evaluate the multinomial likelihood for diagnostic score bins
Description
Evaluate the conditional log likelihood for the diseased and non-diseased score counts at the cutoffs reported by each study.
Usage
dta_threshold_loglik(score_bins, cdf)
Arguments
score_bins |
A data frame such as the |
cdf |
Data frame with columns |
Details
For each study, take differences between successive cumulative probabilities at its reported cutoffs, with endpoints zero and one. If the study omits a cutoff, the corresponding wider bin receives the sum of the probabilities of its constituent intervals.
Each stratum contributes a multinomial probability conditional on its
total. The log likelihood includes the multinomial coefficients and uses
the raw bin counts, including empty bins. Any adjustment columns in
score_bins are ignored. A positive count in a bin with probability
zero gives a log likelihood of -Inf. The supplied probabilities are
treated as fixed for this calculation.
Value
A list with the total log_likelihood and a by_study data
frame with the two stratum contributions (diseased and
non_diseased) and their sum (log_likelihood). Study order follows
first appearance in score_bins.
References
Jones, H. E., Gatsonis, C. A., Trikalinos, T. A., Welton, N. J., and Ades, A. E. (2019). Quantifying how diagnostic test accuracy depends on threshold in a meta-analysis. Statistics in Medicine, 38(24), 4789–4803. doi:10.1002/sim.8301.
See Also
Exploratory Factor Analysis After Correlation Synthesis
Description
Fits an exploratory factor analysis (EFA) model from a synthesized
correlation matrix extracted from a fitted mars object.
Usage
efa_from_synthesis(
mars_object,
n_factors = 1L,
rotation = "varimax",
num_obs = NULL,
synthesis_method = c("model", "average", "weighted"),
synthesis_transform = c("none", "fisher_z"),
missing_corr = c("available", "pairwise", "em"),
attenuation = c("none", "correct"),
reliability = NULL,
reliability_missing = c("error", "skip", "impute_mean", "assume_1"),
pd_adjust = c("none", "eigen_clip", "nearpd"),
pd_tol = 1e-08,
se_method = c("none", "simulation", "bootstrap"),
se_draws = 1000L,
se_seed = NULL,
vcov_source = c("model", "robust"),
factor_retention = c("none", "parallel"),
parallel_n = NULL,
parallel_draws = 200L,
...
)
## S3 method for class 'efa_mars'
summary(object, ...)
## S3 method for class 'efa_mars'
print(x, digits = max(3, getOption("digits") - 3), ...)
Arguments
mars_object |
A fitted object returned by |
n_factors |
Number of latent factors for EFA. |
rotation |
Rotation function or function name, or |
num_obs |
Optional descriptive size; it does not enable a single-sample chi-square test for synthesized correlations. |
synthesis_method |
Correlation synthesis method: |
synthesis_transform |
Optional pooling transform for
|
missing_corr |
Missing-correlation handling for synthesized matrices.
One of |
attenuation |
Attenuation-correction mode for synthesized correlations.
One of |
reliability |
Reliability input used when |
reliability_missing |
Strategy for missing reliability values.
One of |
pd_adjust |
Positive-definite repair for synthesized correlations:
|
pd_tol |
Minimum eigenvalue tolerance used by
|
se_method |
|
se_draws |
Number of uncertainty draws, an integer >= 50. |
se_seed |
Optional seed; the caller's RNG state is restored. |
vcov_source |
Model-based or robust pooled-correlation covariance. |
factor_retention |
|
parallel_n |
User-specified independent-unit count for the parallel-analysis reference distribution. Do not automatically substitute total participant N. |
parallel_draws |
Number of independent normal reference matrices, >= 50. |
... |
Additional arguments passed to |
object |
An object of class |
x |
An object of class |
digits |
Number of digits used when printing numeric results. |
Details
EFA uses maximum-likelihood extraction from stats::factanal() with no
single-sample chi-square test. For oblique rotation, communalities are the
diagonal of L Phi L', and the implied matrix adds uniquenesses. boundary
flags uniquenesses near factanal's default lower bound; inspect the selected
factor count, rotation and residual matrix when this occurs.
Loading uncertainty is conditional on the chosen count and rotation. Named bootstrap correlation draws are used when available; otherwise independent studies/clusters are resampled and the stored synthesis specification is refit. Simulation uses the matched joint normal approximation to pooled correlations. Each admissible loading matrix is aligned to the reference by optimal factor permutation (up to seven factors) and sign matching; larger solutions use greedy matching. Substantial rotational ambiguity requires sensitivity analysis. SEs and loading covariance require at least 50 successful fits and an 80 percent success rate. Alternative pooling or repaired point matrices have no matched sampling covariance, so uncertainty is withheld. Draw matrices are not repaired.
Parallel analysis compares the pooled matrix eigenvalues with the 95th percentile from independent normal reference matrices. It is a descriptive PCA sensitivity at the explicitly chosen unit count, not a calibrated factor-retention test for synthesized correlations. Assess different counts and substantive interpretability.
Value
An object of class efa_mars, with descriptive loadings,
factor_correlations, communalities, implied_matrix
and a fit_note. Oblique solutions use the factor correlation
matrix in communalities and implied covariances. Sample-size-based
chi-square tests are not available for a synthesized matrix.
Examples
fit <- mars(
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"
)
)
efa_from_synthesis(fit, n_factors = 1)
Egger-Type Small-Study-Effects Test
Description
Tests funnel asymmetry directly from an ordinary MARS fit, without fitting a selection model. Retains the parent mean design and clusters inference by study.
Usage
egger_test(
object,
robust_args = list(type = "CR1S", inference = "naive-t"),
cluster = NULL
)
## S3 method for class 'mars_egger'
print(x, digits = 4L, ...)
Arguments
object |
Ordinary mars fit, or pub_bias fit whose ordinary parent is used.
For network models use |
robust_args |
Named controls for the shared robust engine. Defaults to
CR1S covariance and G-1 t inference. See |
cluster |
Optional column naming independent clusters. NULL uses the parent's robustID cluster when stored, otherwise studyID. This determines inference groups, not the regression weights. Missing cluster identifiers are rejected. |
x |
Egger-test result. |
digits |
Significant digits for printing. |
... |
Unsupported print arguments are rejected. |
Details
Fits y/\mathrm{SE} on a constant asymmetry intercept and the original mean design
divided by sampling SE, using ordinary least squares. No additional inverse-
variance weights are applied on this standardized scale. With an intercept-only
parent this equals raw-effect regression on sampling SE with inverse-variance
weights. QR computation scales design columns for numerical stability.
The null is a zero asymmetry coefficient, not absence of publication bias.
Moderators are retained; study-cluster robust inference accommodates dependence
within studies but does not remove confounding by unmodeled effect modifiers.
Fewer than ten independent studies and little SE variation are flagged. Ten
is a rule of thumb. Rank deficiency, invalid SEs or reference degrees of freedom
make inference unavailable. Original Egger-type tests can show artefactual
asymmetry for SMDs and odds ratios because effects and SEs can be coupled.
Nonsignificance does not exclude missing evidence. Assess effect-measure
suitability and interpret alongside study characteristics and funnel plots.
Value
A mars_egger list with ok, asymmetry intercept, SE, statistic, reference degrees of freedom, p_value, complete coefficient/design/covariance information, study counts and interpretation diagnostics. Unavailable tests have ok=FALSE and a reason. Print displays the asymmetry test and diagnostic notes.
References
Egger et al. (1997). Bias in meta-analysis detected by a simple, graphical test. BMJ, 315, 629-634. doi:10.1136/bmj.315.7109.629.
Examples
fit <- mars(bcg,studyID="trial",effectID=NULL,sample_size=NULL,formula=yi~1,
variance="vi",varcov_type="univariate",structure="univariate")
egger_test(fit)
Available effect-size computation routes
Description
Lists supported measure/design/input combinations for compute_es(), with
formulas, required inputs, defaults, assumptions and source references.
Usage
es_methods()
Details
This function returns a registry; it does not calculate or synthesize effects. Filter its rows to find the measure, design and input you intend to use, then supply that combination explicitly to compute_es. Matching numerical degrees of freedom alone does not establish design eligibility.
In formulas, n1/n2 are arm sizes, d is uncorrected standardization, yi is the analysis-scale estimate, J is the selected bias-correction factor, and R2 is full-model unadjusted R-squared. For binary comparisons a/b are group 1 events/non-events and c/d are group 2 events/non-events. Symbols named d thus have a different meaning in binary and standardized-mean formulas. See compute_es for complete definitions, boundary policies and reconstruction rules.
Normal Wald intervals and most sampling variances are approximations. Exact
Hedges correction does not make the variance or confidence interval exact.
Log and Fisher-z measures have analysis-scale variances; back-transformed
display estimates must not be paired with those variances. Dependence between
effect rows is unspecified until explicitly constructed with
compute_es_covariance(). transform_es() propagates uncertainty through an
explicit transformation. The registry covers the supported routes and does
not claim complete coverage of Lipsey and Wilson (2001), Appendix B.
Value
A data frame with one row per supported route. Columns are:
- route_id, method_version
Route identifier and computation-specification version. These identify the calculation, not the installed package version.
- measure, design, input, status
Target measure, eligible design, selected input route, and implementation status.
- required, optional
Inputs the user must supply, and optional route controls with their defaults. Study/effect IDs are optional for all routes.
- estimate_formula, variance_formula
Point-estimate and sampling-variance formulas. Variance formulas are labelled by method; reconstructed SDs and any explicitly applied pseudo-counts are used where appropriate.
- variance_methods, default_variance_method, default_correction
Accepted variance methods and defaults when the corresponding arguments are omitted. SMD/GLASS default to exact Hedges correction; other measures use none.
- analysis_scale, effect_direction
Scale of yi/vi and contrast direction.
- assumptions
Design and distribution requirements; these are declarations to verify in the source study, not assumptions tested by this function.
- reference, source_url, source_locator
References and source locations. A missing URL means the route preserves a study's reported estimate/SE.
See Also
compute_es(), aggregate_es_subgroups(), compute_es_covariance(),
transform_es()
Examples
methods <- es_methods()
methods[methods$measure == "SMD",
c("input", "required", "default_correction", "default_variance_method")]
methods[methods$design == "ordinary_regression",
c("measure", "input", "analysis_scale")]
methods[methods$input == "means_ci", c("measure", "required", "optional")]
Master Estimation Function
Description
The primary estimation function for conducting the optimization. The function is typically called through the mars function, but can be called here directly.
Usage
estimation(
formula = NULL,
scale_formula = NULL,
effect_name = NULL,
studyID = NULL,
effectID = NULL,
variance = NULL,
data,
estimation_method = "REML",
optim_method = "L-BFGS-B",
structure = "UN",
varcov_type,
weights = NULL,
intercept = FALSE,
N = NULL,
missing = "remove",
robustID = NULL,
robust_args = list(),
unique_n = NULL,
lasso = FALSE,
lasso_args = list(lambda_grid = 10^seq(1, -3, length.out = 5), K = 5, all_lasso_metrics
= FALSE, lambda_tolerance = 0),
multivariate_covs = NULL,
tau2 = NULL,
tol = 1e-10,
control = list(maxit = 1000L),
vcov_method = c("gls", "observed"),
...
)
Arguments
formula |
The formula used for specifying the fixed and random structure. Used for univariate and multilevel structures. |
scale_formula |
Optional one-sided formula for modeling the
log-heterogeneity in location-scale models. Currently supported for
|
effect_name |
Character string representing the name of the effect size column in the data. |
studyID |
Character string representing the study ID |
effectID |
Character string representing the effect size ID |
variance |
Character string representing the name of the variance of the effect size in the data. |
data |
Data used for analysis |
estimation_method |
Type of estimation used, either "REML" or "MLE", REML is the default |
optim_method |
Optimization method that is passed to the optim function. Default is 'L-BFGS-B'. |
structure |
Between studies covariance structure, default is "UN" or unstructured. See details for more specifics. |
varcov_type |
Type of variance covariance matrix computed. Default is 'cor_weighted' for correlations or 'smd_outcome' for standardized mean differences. |
weights |
User specified matrix of weights. |
intercept |
Whether a model intercept should be specified, default is FALSE meaning no intercept. See details for more information. |
N |
Character string representing the sample size of the studies. |
missing |
What to do with missing data. Use |
robustID |
A character vector specifying the cluster group to use for computing the robust standard errors. |
robust_args |
Named list controlling robust covariance and inference.
Supported entries include |
unique_n |
A numeric vector of unique sample sizes, calculated internally. |
lasso |
TRUE/FALSE indicator that specifies if lasso results are returned. TRUE means lasso results will be run, if number of predictors is less than number of effect sizes, both lasso and non-lasso results will be returned, if number of predictors is equal to or greater than the number of effect sizes, the lasso results will only be returned. |
lasso_args |
A list of LASSO specific arguments.
|
multivariate_covs |
A one-sided formula to specify the covariates used in a multivariate analysis. |
tau2 |
Optional user-supplied between-study variance or covariance.
If |
tol |
Tolerance for estimating, passed to |
control |
Named ordinary-optimizer controls. The default allows 1000
iterations. For example, |
vcov_method |
Model-based coefficient covariance: |
... |
Additional arguments to pass to |
Value
Output is a named list; The output returns the estimated parameters,
fit statistics, estimation inputs.
For multivariate fits, QE$components contains marginal homogeneity
tests for each outcome, fitted separately using its sampling covariance.
These tests do not generally sum to the joint Q. QE$joint_contributions
allocates the joint Q by outcome as sums of r \odot (S^{-1}r); these
contributions can be negative and have no separate chi-square test.
Both are data frames that can be exported with utils::write.csv().
References
Harville, D. A. (1977). Maximum likelihood approaches to variance component estimation and to related problems. Journal of the American Statistical Association, 72(358), 320–338. doi:10.1080/01621459.1977.10480998.
Patterson, H. D., and Thompson, R. (1971). Recovery of inter-block information when block sizes are unequal. Biometrika, 58(3), 545–554. doi:10.1093/biomet/58.3.545.
Examples
fit <- estimation(
formula = yi ~ 1,
effect_name = "yi",
studyID = "study",
variance = "vi",
data = teacher_expectancy,
structure = "univariate",
varcov_type = "univariate"
)
fit$coefficients
Estimate Regression Coefficients from a Correlation Matrix
Description
Deprecated. Use model_fit() for a model fitted to a single correlation
matrix or path_model() for a model fitted after meta-analytic synthesis.
Usage
find_B(model_input, R)
Arguments
model_input |
Model input as a character string. Multiple models need
to be on their own line. Regression syntax uses a lavaan-like
|
R |
A named correlation matrix, typically the pooled correlation matrix
extracted from a fitted |
Details
Each regression line is parsed independently. For a statement such as
y ~ x1 + x2, the function reorders R into predictor and
outcome blocks and computes the standardized least-squares coefficients as
R_{xx}^{-1} R_{xy}. Blank lines and comment lines are ignored by the
lower-level model parser.
Value
A list of named vectors of standardized regression coefficients, one
element per regression equation in model_input.
Find regression coefficients
Description
Deprecated. Use model_fit() for a model fitted to a single correlation
matrix or path_model() for a model fitted after meta-analytic synthesis.
Usage
find_reg_coef(model_input, R, ...)
Arguments
model_input |
Model input as a character string. Multiple models need to be on their own line. See details for specification. |
R |
A correlation matrix, most likely this will be the average correlation matrix outputted from the metafor package. |
... |
Currently not used |
Value
A vector of regression coefficient estimates.
Forest Plot for Meta-Analysis Results
Description
Generates a forest plot from a meta-analysis result object, optionally grouped by a specified subgrouping variable.
Usage
forest_plot(
mars_object,
subgroups = NULL,
z_dist = TRUE,
xlab = "Effect Size",
main = "Forest Plot",
study_header = "Study",
subgroup_header = "Group",
es_header = "ES (SE)",
note = NULL,
ci_level = 0.95,
marker_scale = 2,
font_cex = 0.8,
legend_position = "top",
legend_title = NULL,
legend_inset = c(0, -0.2),
main_adj = 0.5,
main_line = NULL
)
Arguments
mars_object |
A fitted mars object. |
subgroups |
Optional. Name of the column in |
z_dist |
Logical. Whether to use the normal distribution for confidence intervals. If |
xlab |
Label for the x-axis. Defaults to "Effect Size". |
main |
Title of the forest plot. Defaults to "Forest Plot". |
study_header |
Label for the column showing study names. Defaults to "Study". |
subgroup_header |
Label for the subgroup column (if used). Defaults to "Group". |
es_header |
Label for the effect size column. Defaults to "ES (SE)". |
note |
Optional. Text or named list providing a summary note (for
example, effect, SE, |
ci_level |
Confidence level for the interval bounds. Defaults to 0.95. |
marker_scale |
Numeric multiplier for marker size. Defaults to 2. |
font_cex |
Numeric scaling for text labels. Defaults to 0.8. |
legend_position |
Legend position for subgroup labels. Use |
legend_title |
Optional subgroup legend title. |
legend_inset |
Numeric inset passed to |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
Details
The function sorts studies by effect size and draws each study as a point with a confidence interval.
If subgroups is provided, distinct plot symbols are used for each group and a legend is added.
Optionally, a summary note can be added below the plot using the note argument.
Value
A base R forest plot is rendered to the current graphics device.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
forest_plot(fit, subgroups = "setting")
Funnel Plot for Publication-Bias Models
Description
Draws a funnel directly from an ordinary mars fit, a pub_bias fit, or a
precomputed trim_fill() result. Selection fitting is not required.
Usage
funnel_plot(object, ...)
## S3 method for class 'pub_bias'
funnel_plot(
object,
y_axis = c("se", "precision"),
center = c("adjusted", "observed", "none"),
show_contours = TRUE,
contour_levels = c(0.9, 0.95),
point_cex = 0.9,
point_col = "#1F4E79",
xlab = "Effect size",
ylab = NULL,
main = "Funnel Plot",
center_line_col = "gray40",
contour_col = "gray65",
main_adj = 0.5,
main_line = NULL,
trim_fill = FALSE,
trim_fill_args = list(),
filled_pch = 21,
filled_col = "#C0392B",
show_legend = TRUE,
...
)
## S3 method for class 'mars'
funnel_plot(object, ...)
## S3 method for class 'mars_trimfill'
funnel_plot(object, trim_fill = TRUE, trim_fill_args = list(), ...)
Arguments
object |
Ordinary mars fit, pub_bias fit or mars_trimfill result. Network
fits use |
... |
Named graphics arguments passed to |
y_axis |
One of |
center |
adjusted uses the ordinary fitted intercept/reference prediction for mars, the selection-adjusted reference for pub_bias, or the augmented estimate when trim_fill=TRUE. References use predictor zero, and an intercept- free model gives zero. observed uses only observed studies' marginal inverse- sampling-variance mean; none omits the line. These are not row-specific moderator predictions or dependence-adjusted pooled means. |
show_contours |
Logical; if |
contour_levels |
Numeric vector of contour levels (e.g., |
point_cex |
Point size scaling. |
point_col |
Point color. |
xlab |
Label for x-axis. |
ylab |
Optional y-axis label. If |
main |
Plot title. |
center_line_col |
Center-line color. |
contour_col |
Contour-line color. |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
trim_fill |
Logical; TRUE computes |
trim_fill_args |
Named controls passed to |
filled_pch, filled_col |
Symbol and border color for hypothetical studies; observed studies use solid circles in point_col. Default filled points are open. |
show_legend |
Logical; add observed/imputed symbol labels with trim-and-fill. |
Details
Pseudo contours are center plus/minus qnorm((1+level)/2)*sampling SE.
They are descriptive sampling guides, omit heterogeneity and uncertainty in
the center, and are not simultaneous intervals or null-significance contours.
Raw effects with moderators or multiple outcomes can have different expected
means; interpret their combined funnel cautiously or plot suitable strata.
SE axes decrease upwards; precision axes increase upwards. Trim-and-fill is
restricted to independent, intercept-only univariate models and preserves the
parent's ML/REML or fixed heterogeneity convention. Filled effects reflect
selected observed effects around a trimmed symmetry center and retain their
variances. Filling is a sensitivity analysis, not recovery of missing studies.
Without trimming, ordinary multilevel/multivariate raw funnels remain descriptive
and do not display study-cluster-adjusted sampling uncertainty. See trim_fill()
and egger_test() for assumptions, limitations and the independent test.
Value
Invisibly returns plotted effect, se, fitted and imputed columns, plus source-row/study metadata with trim-and-fill. The trim_fill attribute stores its full sensitivity result (NULL for ordinary plots); center stores the actual guide center, including NA when omitted.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
funnel_plot(fit)
egger_test(fit)
funnel_plot(fit,trim_fill=TRUE,trim_fill_args=list(side="left"))
bias_fit <- publication_bias(fit)
funnel_plot(bias_fit)
Evidence Gap Map Plot
Description
Creates a base-R evidence gap map with outcomes and interventions on the axes, bubble sizes representing number of studies, and labels inside bubbles representing number of effect sizes.
Usage
gap_map_plot(
data,
intervention,
outcome,
study_id = NULL,
effect_id = NULL,
n_studies = NULL,
n_effects = NULL,
switch_axes = FALSE,
intervention_order = NULL,
outcome_order = NULL,
bubble_range = c(1.5, 7),
bubble_col = "#2E6F95",
bubble_border = "gray20",
text_col = "white",
display_effect_labels = TRUE,
effect_label_cex = 0.9,
bubble_size_by = c("studies", "effects"),
label_value = c("effects", "studies"),
draw_mode = c("both", "bubbles_only", "labels_only"),
show_grid = TRUE,
grid_col = "gray90",
show_size_legend = TRUE,
size_legend_title = NULL,
size_legend_values = NULL,
main = "Evidence Gap Map",
xlab = NULL,
ylab = NULL,
cex_axis = 0.85,
cex_main = 1,
size_legend_position = "outside_right",
size_legend_inset = 0,
main_adj = 0.5,
main_line = NULL
)
Arguments
data |
A data frame. |
intervention |
Character string naming the intervention column. |
outcome |
Character string naming the outcome column. |
study_id |
Optional character string naming the study ID column (for
long-format input). If omitted, |
effect_id |
Optional character string naming the effect size ID column
(for long-format input). If omitted and |
n_studies |
Optional character string naming a numeric column with pre-aggregated study counts per cell. |
n_effects |
Optional character string naming a numeric column with pre-aggregated effect-size counts per cell. |
switch_axes |
Logical. If |
intervention_order |
Optional character vector for intervention ordering. |
outcome_order |
Optional character vector for outcome ordering. |
bubble_range |
Numeric vector of length 2 with minimum and maximum point
sizes ( |
bubble_col |
Fill color for bubbles. |
bubble_border |
Border color for bubbles. |
text_col |
Text color for the number of effect sizes inside bubbles. |
display_effect_labels |
Logical. If |
effect_label_cex |
Numeric scaling for effect-size labels. |
bubble_size_by |
Which metric controls bubble size:
|
label_value |
Which metric is shown as text labels:
|
draw_mode |
What to draw: |
show_grid |
Logical. If |
grid_col |
Color for grid lines. |
show_size_legend |
Logical. If |
size_legend_title |
Title for the bubble-size legend. If |
size_legend_values |
Optional numeric vector of study-count values used
in the size legend. If |
main |
Main title. |
xlab |
Optional x-axis label. If |
ylab |
Optional y-axis label. If |
cex_axis |
Axis label scaling. |
cex_main |
Main title scaling. |
size_legend_position |
Legend position keyword or numeric coordinates.
Use |
size_legend_inset |
Numeric inset passed to |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
Details
The function supports both long-format input (one row per effect size) and pre-aggregated input.
Value
Invisibly returns a list with:
- data
Aggregated data used for plotting (
intervention,outcome,n_studies,n_effects).- x_levels
Ordered x-axis levels.
- y_levels
Ordered y-axis levels.
Examples
gap_dat <- data.frame(
study = c("S1", "S1", "S2", "S3", "S3", "S4", "S5"),
effect = c("E1", "E2", "E3", "E4", "E5", "E6", "E7"),
intervention = c("Tutoring", "Tutoring", "Tutoring", "Coaching", "Coaching", "App", "App"),
outcome = c("Math", "Math", "Reading", "Math", "Reading", "Reading", "Math"),
stringsAsFactors = FALSE
)
gap_map_plot(
data = gap_dat,
intervention = "intervention",
outcome = "outcome",
study_id = "study",
effect_id = "effect"
)
gap_map_plot(
data = gap_dat,
intervention = "intervention",
outcome = "outcome",
study_id = "study",
effect_id = "effect",
switch_axes = TRUE
)
Harmonized Standardized Mean Differences
Description
Computes traditional standardized mean differences (SMDs) and harmonized
standardized mean differences (HSMDs) by replacing observed group standard
deviations with common coefficient-of-variation benchmarks. Pooled summaries
are estimated with mars(), allowing the harmonized effect sizes to be
analyzed with univariate, multivariate, or multilevel model structures.
Usage
hsmd(
data,
mT,
sdT,
nT,
mC,
sdC,
nC,
study = NULL,
probs = c(0.25, 0.5, 0.75),
measure = c("d", "g"),
structure = "univariate",
formula = NULL,
effectID = NULL,
sample_size = NULL,
varcov_type = NULL,
variance = NULL,
cv_by = NULL,
cv_benchmarks = NULL,
estimation_method = "REML",
...
)
## S3 method for class 'hsmd'
print(x, digits = max(3, getOption("digits") - 3), ...)
Arguments
data |
A data frame containing treatment and control summary statistics. |
mT, sdT, nT |
Unquoted column names for treatment-group mean, standard deviation, and sample size. Observed values must be finite numeric values; sample sizes must be integers greater than 1 and SDs non-negative. Missing SDs are permitted when benchmarks can be estimated or supplied. |
mC, sdC, nC |
Unquoted column names for control-group mean, standard deviation, and sample size. |
study |
Optional unquoted column name identifying studies. If omitted, a sequential study identifier is created. |
probs |
Numeric vector of coefficient-of-variation quantiles to use for
harmonization. Defaults to |
measure |
Effect-size estimate used in the fitted |
structure |
Model structure passed to |
formula |
Optional model formula for univariate or multilevel models.
The left-hand side is replaced internally with each SMD/HSMD effect-size
column, so callers may supply either a one-sided formula (for example
|
effectID |
Optional column identifying dependent effect sizes for multivariate models. |
sample_size |
Optional sample-size column passed to |
varcov_type |
Within-study variance-covariance type passed to |
variance |
Optional variance column used when the selected
|
cv_by |
Optional unquoted column used to compute coefficient-of-variation benchmarks within subgroups, such as outcomes or domains. Group IDs cannot be missing. One or several quantiles may be requested. |
cv_benchmarks |
Optional named list with elements |
estimation_method |
Estimation method passed to |
... |
Additional arguments passed to downstream print methods. |
x |
An object of class |
digits |
Number of digits used when printing numeric results. |
Details
HSMD is a sensitivity analysis of standardizer variability. CVs use
s/|m|; harmonized SDs use |m|\times CV_q. Means must be nonzero
and the outcome needs a meaningful ratio-scale origin. No fixed numerical
floor is used, so positive changes of measurement units preserve the results.
Negative means trigger a scale-suitability warning. A shift of origin can
change HSMD, even when it leaves conventional SMD unchanged.
Conventional d uses the pooled SD and the large-sample variance
1/n_T+1/n_C+d^2/[2(n_T+n_C)]. The approximate correction is
J=1-3/[4(n_T+n_C-2)-1], with g=Jd and v_g=J^2v_d.
These conventions are also applied to harmonized effects as sensitivity
calculations; they do not propagate uncertainty in estimated CV benchmarks.
They should not be interpreted as unconditional inference for an independently
validated new effect-size estimator.
Each model receives only its required analysis columns. A missing original
SD does not exclude a computable harmonized effect, and unrelated missing
columns do not affect fitting. Required moderators still follow the selected
missing policy. Compare n_effects and n_studies before comparing models:
changes in the study set can accompany changes in the standardizer. At least
two usable effects are required per fit; use hsmd_effect_sizes() to inspect
effects when a model cannot be fitted. avwW uses the fitted covariance
diagonals. Full covariance and heterogeneity information remains in models.
Value
A list with class "hsmd" containing:
- summary
Coefficient estimates, uncertainty and actual analysis counts.
tau2andI2are populated only for univariate models.- heterogeneity
Separate named variance components for each model, without truncating or assigning components to regression coefficients.
- cv_benchmarks
Treatment and control CV benchmarks used.
- inference
A reminder of the conditional sensitivity interpretation.
- effect_sizes
Data frame of study-level effect sizes and variances.
- data
Original input data with added coefficient-of-variation and harmonized SD columns. Internal
nt/nccolumns always reflect the explicitly selected sample-size columns.- models
Named list of fitted
marsmodel objects.- quantiles
Named numeric vector of the requested harmonization quantiles.
References
Jung, J. and Aloe, A. M. (2025). Standardized Mean Differences: Not So Standard After All. Campbell Systematic Reviews, 21, e70056. doi:10.1002/cl2.70056.
Examples
ex1 <- hsmd(
data = hsmd_example_1,
mT = mT, sdT = sdT, nT = nT,
mC = mC, sdC = sdC, nC = nC,
study = Study
)
ex1$summary
ex2 <- hsmd(
data = hsmd_example_2,
mT = mT, sdT = sdT, nT = nT,
mC = mC, sdC = sdC, nC = nC,
study = Study
)
head(ex2$effect_sizes)
Compute HSMD effect-size columns
Description
Compute HSMD effect-size columns
Usage
hsmd_effect_sizes(
data,
mT,
sdT,
nT,
mC,
sdC,
nC,
probs = c(0.25, 0.5, 0.75),
cv_by = NULL,
cv_benchmarks = NULL
)
Arguments
data |
A data frame containing treatment and control summary statistics. |
mT, sdT, nT |
Unquoted column names for treatment-group mean, standard deviation, and sample size. Observed values must be finite numeric values; sample sizes must be integers greater than 1 and SDs non-negative. Missing SDs are permitted when benchmarks can be estimated or supplied. |
mC, sdC, nC |
Unquoted column names for control-group mean, standard deviation, and sample size. |
probs |
Numeric vector of coefficient-of-variation quantiles to use for
harmonization. Defaults to |
cv_by |
Optional unquoted column used to compute coefficient-of-variation benchmarks within subgroups, such as outcomes or domains. Group IDs cannot be missing. One or several quantiles may be requested. |
cv_benchmarks |
Optional named list with elements |
Value
A list with prepared data, effect_sizes, probs, prob_names,
and coefficient-of-variation benchmarks.
Examples
hsmd_cols <- hsmd_effect_sizes(
hsmd_example_1,
mT = mT,
sdT = sdT,
nT = nT,
mC = mC,
sdC = sdC,
nC = nC
)
names(hsmd_cols$effect_sizes)
HSMD Example 1 Data
Description
Example dataset from the HSMD supplementary materials containing treatment and control summary statistics for 16 studies.
Usage
hsmd_example_1
Format
A data frame with 16 rows and 7 columns:
- Study
Study label.
- mT
Treatment-group mean.
- sdT
Treatment-group standard deviation.
- nT
Treatment-group sample size.
- mC
Control-group mean.
- sdC
Control-group standard deviation.
- nC
Control-group sample size.
Examples
hsmd_example_1
HSMD Example 2 Data
Description
Example dataset from the HSMD supplementary materials containing treatment and control summary statistics for 12 studies.
Usage
hsmd_example_2
Format
A data frame with 12 rows and 7 columns:
- Study
Study label.
- mT
Treatment-group mean.
- sdT
Treatment-group standard deviation.
- nT
Treatment-group sample size.
- mC
Control-group mean.
- sdC
Control-group standard deviation.
- nC
Control-group sample size.
Examples
hsmd_example_2
Influence Diagnostics for MARS Models
Description
Compute case-level and grouped influence summaries using studentized residuals, leverage, and Cook's distance.
Usage
influence_diagnostics(object, cluster = NULL, outcome = NULL, top_n = 10L)
Arguments
object |
A fitted |
cluster |
Optional cluster column in |
outcome |
Optional outcome column in |
top_n |
Number of top influential rows to retain. |
Value
A list with row-level influence diagnostics, grouped summaries, thresholds, and top influential rows.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
influence_diagnostics(fit, top_n = 5)
Improvement rate difference for binary single-case outcomes
Description
Computes the intervention minus baseline improvement rate and its binomial risk-difference variance.
Usage
ird_computation(
data,
studyID,
subjectID,
outcome_name,
phase_name,
phase_order = NULL,
improvement = c("increase", "decrease"),
na_option = "listwise"
)
Arguments
data |
Data frame containing repeated observations. |
studyID, subjectID, outcome_name, phase_name |
Character strings naming the study, case, outcome, and phase columns. |
phase_order |
Character vector giving the baseline and intervention
labels, in that order. If |
improvement |
Whether an increase or decrease in the outcome is beneficial. |
na_option |
Currently only |
Details
Outcomes must be coded 0/1. With improvement = "increase", one is
treated as improvement; with improvement = "decrease", zero is treated as
improvement. The variance assumes independent binary observations.
Value
A data frame with the improvement rate difference in yi and the
independence-based binomial variance in vi.
Examples
dat <- data.frame(study = "S1", case = "A", phase = rep(c("A", "B"), each = 4),
outcome = c(0, 0, 1, 0, 1, 1, 1, 1))
ird_computation(dat, "study", "case", "outcome", "phase")
Jackknife network meta-analysis
Description
Performs one leave-one-study-out jackknife omission and refits
network_meta.
Usage
jackknife_network_meta(
leave_out,
data,
study_id,
treatment_1,
treatment_2,
effect,
variance,
on_error = c("warn", "stop", "keep"),
...
)
Arguments
leave_out |
Study ID value to omit. |
data |
A contrast-level network meta-analysis data frame. |
study_id |
Character string naming the study ID column. |
treatment_1 |
Character string naming the first treatment column. |
treatment_2 |
Character string naming the second treatment column. |
effect |
Character string naming the effect-size column. |
variance |
Character string naming the sampling-variance column. |
on_error |
How fitting errors should be handled. |
... |
Additional arguments passed to |
Value
A fitted "nma_mars" object, or an "nma_resample_error"
object when fitting fails and errors are retained.
Examples
nma_dat <- data.frame(
study = c("S1", "S2", "S3", "S4"),
treatment_1 = c("A", "A", "B", "A"),
treatment_2 = c("B", "C", "C", "B"),
effect = c(0.20, 0.35, 0.10, 0.15),
variance = c(0.04, 0.05, 0.04, 0.06)
)
jack_fit <- jackknife_network_meta(
leave_out = "S1",
data = nma_dat,
study_id = "study",
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
effect = "effect",
variance = "variance",
model_type = "wls"
)
Segmented level-change and slope-change effects for single-case data
Description
Fits a segmented AB time-series model separately to each study-case series and returns the immediate intervention level change and change in time slope, with model-based variances and their covariance.
Usage
level_slope_computation(
data,
studyID,
subjectID,
outcome_name,
phase_name,
time_name,
phase_order = NULL,
improvement = c("increase", "decrease"),
correlation = c("independence", "ar1"),
na_option = "listwise"
)
Arguments
data |
Data frame containing repeated observations. |
studyID, subjectID, outcome_name, phase_name |
Character strings naming the study, case, outcome, and phase columns. |
time_name |
Character string naming the ordered measurement-time column. |
phase_order |
Character vector giving the baseline and intervention
labels, in that order. If |
improvement |
Whether an increase or decrease in the outcome is beneficial. |
correlation |
Either |
na_option |
Currently only |
Details
This function supports a single transition from baseline to intervention: all baseline times must precede all intervention times. The AR(1) option estimates rho from ordinary least-squares residuals; its reported variance treats that estimated rho as fixed and is therefore approximate.
Value
A data frame with two rows per study-case: level_change and
slope_change. cov_level_slope is repeated on both rows to allow the two
estimates to be retained as dependent effects in later synthesis.
Examples
dat <- data.frame(study = "S1", case = "A", time = 1:8,
phase = rep(c("A", "B"), each = 4),
outcome = c(1, 2, 2, 3, 5, 6, 7, 8))
level_slope_computation(dat, "study", "case", "outcome", "phase", "time")
Log response ratio for single-case phase contrasts
Description
Computes the log response ratio between intervention and baseline phase means and a delta-method sampling variance.
Usage
log_response_ratio_computation(
data,
studyID,
subjectID,
outcome_name,
phase_name,
phase_order = NULL,
improvement = c("increase", "decrease"),
continuity = 0,
na_option = "listwise"
)
Arguments
data |
Data frame containing repeated observations. |
studyID, subjectID, outcome_name, phase_name |
Character strings naming the study, case, outcome, and phase columns. |
phase_order |
Character vector giving the baseline and intervention
labels, in that order. If |
improvement |
Whether an increase or decrease in the outcome is beneficial. |
continuity |
Non-negative value added to every outcome before computing phase means. Use a positive value only when a documented continuity adjustment is appropriate for zero-valued rate or count outcomes. |
na_option |
Currently only |
Details
Both phases require at least two observations for variance estimation.
Outcomes must be positive after adding continuity. The variance assumes
independent observations within and between phases.
Value
A data frame with yi equal to
\log(\bar y_{\mathrm{intervention}}/\bar y_{\mathrm{baseline}})
(or its sign-reversed version for decreasing outcomes) and delta-method
variance vi.
Examples
dat <- data.frame(study = "S1", case = "A", phase = rep(c("A", "B"), each = 3),
outcome = c(2, 3, 4, 4, 6, 8))
log_response_ratio_computation(dat, "study", "case", "outcome", "phase")
Fit MARS Meta-Analytic Models
Description
Primary interface for fitting univariate, multivariate/correlation, standardized-mean-difference, and multilevel meta-analytic models. The function inspects the supplied modeling arguments and routes the data to the appropriate estimator.
Usage
mars(
data,
studyID,
effectID,
sample_size,
effectsize_type = NULL,
formula = NULL,
scale_formula = NULL,
variable_names = NULL,
effectsize_name = NULL,
estimation_method = "REML",
variance = NULL,
varcov_type,
weights = NULL,
structure = "UN",
intercept = FALSE,
missing = "remove",
optim_method = "L-BFGS-B",
robustID = NULL,
robust_args = list(),
multivariate_covs = NULL,
lasso = FALSE,
lasso_args = list(),
tau2 = NULL,
tol = 1e+07,
control = list(maxit = 1000L),
vcov_method = c("gls", "observed"),
...
)
Arguments
data |
Data frame containing the effect sizes, sampling variances or inputs needed to construct sampling covariance matrices, study identifiers, and any moderators. |
studyID |
Character string naming the study-level cluster column. |
effectID |
Character string naming an effect-size or outcome identifier
column for dependent-effect workflows. Use |
sample_size |
Character string naming the study sample-size column. This
is required for correlation and some standardized-mean-difference
covariance estimators and can be |
effectsize_type |
Optional effect-size family for non-formula workflows.
Use |
formula |
Model formula used for univariate and multilevel models. The
left-hand side is the effect-size column. Fixed-effect moderators appear on
the right-hand side. Multilevel models can add random effects with
lme4-style syntax such as |
scale_formula |
Optional one-sided formula for modeling the
log-heterogeneity in location-scale models. Currently supported for
|
variable_names |
Vector of character strings naming effect-size columns
for multivariate/correlation workflows. For correlations, names should
identify the variable pair separated by an underscore, for example
|
effectsize_name |
Character string representing the name of the effect size column in the data. |
estimation_method |
Estimation method. Use |
variance |
Character string naming the sampling-variance column for formula-based models. |
varcov_type |
Type of within-study variance-covariance matrix to use or
construct. Common values include |
weights |
Optional positive-definite inverse sampling covariance matrix, aligned with original input rows. It replaces within-study sampling covariance; fitted heterogeneity is added separately. Matrices coupling study blocks and supplied weights for expanded correlation inputs are unsupported. When supplied, these weights override the internally constructed within-study covariance for the corresponding analysis path. |
structure |
Between-study heterogeneity structure. Use
|
intercept |
Logical; controls whether the multivariate design matrix
includes an intercept. Formula-based univariate and multilevel models use
the intercept implied by |
missing |
Missing-data handling mode. Use |
optim_method |
Optimization method that is passed to the optim function. Default is 'L-BFGS-B'. |
robustID |
Optional character string naming a cluster variable for cluster-robust standard errors when supported by the fitted workflow. |
robust_args |
Named list controlling robust covariance and small-sample inference. Defaults to CR2 covariance with Satterthwaite coefficient tests. |
multivariate_covs |
Optional one-sided formula specifying moderators for
multivariate/correlation workflows, for example |
lasso |
Logical. TRUE delegates to |
lasso_args |
Named list of tuning arguments accepted by |
tau2 |
Optional user-supplied between-study variance or covariance.
If |
tol |
Optimization tolerance forwarded to the L-BFGS-B |
control |
Named ordinary-optimizer controls. The default allows 1000
iterations. For example, |
vcov_method |
Model-based coefficient covariance: |
... |
Reserved for future extensions. |
Details
With lasso=TRUE, the fit is exactly the mars_lasso() analysis for the same
inputs and tuning controls. Formula inputs default to structure='univariate';
specify 'multilevel' for a nested random-intercept formula. Effect-size inputs
accept the omitted structure or an explicit
'multivariate' or 'DIAG1', all using outcome-specific diagonal heterogeneity.
Explicit UN and DIAG2 structures are unsupported for LASSO. Only cor and smd
effect-size families are supported. Correlations use Fisher-z fitting by
default, with matched transformed sampling covariance and response-scale
predictions. Responses in formula fits are not automatically standardized;
reported coefficients retain the supplied response and predictor units.
See mars_lasso() for the normalized penalized ML objective, grouped CV,
convergence checks and selection interpretation.
LASSO does not support scale_formula, weights, tau2, robustID, nonempty robust_args, intercept=TRUE or optimizers other than L-BFGS-B. These options are rejected rather than ignored. Use heterogeneity='none' in lasso_args to fix all heterogeneity components at zero. Its result supports summary(), coef(), predict() and plot() methods for mars_lasso; ordinary mars inference and diagnostics do not apply. An ordinary fit of selected terms requires a separate lasso=FALSE call and does not account for moderator selection.
The main analysis paths are:
Formula-based univariate models: provide
formula,variance,varcov_type = "univariate", andstructure = "univariate".Formula-based multilevel models: provide a random-effect
formula,variance,varcov_type = "multilevel", andstructure = "multilevel".Correlation synthesis: provide
effectsize_type = "cor",sample_size,variable_names, and an appropriate correlationvarcov_type.Non-correlation metric workflows: provide
effectsize_type,effectsize_name, and the columns required by the selected metric-specificvarcov_type.
When multiple effect sizes are available within a study, effectID,
variable_names, random-effect terms, and the selected
varcov_type determine how within-study dependence and between-study
heterogeneity are represented. If a user-supplied weights matrix or
tau2 value is provided, mars() treats those as fixed inputs for
the corresponding part of the model rather than estimating or constructing
them internally.
The core estimator treats the observed effect-size vector in study i
as approximately multivariate normal,
y_i \sim N(X_i \beta, V_i),
where X_i is the fixed-effect design matrix and V_i is the
model-implied marginal covariance matrix. The matrix V_i is the sum of
the within-study sampling covariance matrix S_i and a between-study
heterogeneity component. For univariate models this component is a scalar
\tau^2; for multivariate models it is the selected covariance structure
across outcomes; and for multilevel models it is assembled from random-effect
design matrices as
V_i = S_i + \sum_j \tau_j^2 Z_{ij} Z_{ij}'.
Location-scale models replace constant heterogeneity components with
log-linear variance models, so study-specific components are computed as
\tau_i^2 = \exp(W_i \gamma).
For maximum likelihood (estimation_method = "MLE"), mars()
minimizes the deviance-scale objective
\sum_i \left\{\log |V_i| +
(y_i - X_i \beta)' V_i^{-1} (y_i - X_i \beta)\right\},
omitting constants that do not affect the optimizer. For restricted maximum
likelihood (estimation_method = "REML"), the objective adds the usual
fixed-effect adjustment
\log |X' V^{-1} X|,
where X' V^{-1} X = \sum_i X_i' V_i^{-1} X_i. This penalizes the
likelihood for estimating the fixed effects and is the default estimator.
Optimization is performed with optim. The default
optim_method = "L-BFGS-B" is used because variance components and
covariance-structure parameters require box constraints. Variance parameters
are constrained to be positive with a lower bound of 1e-6; correlation
parameters in structured covariance models are bounded to their allowable
ranges when the structure supplies such bounds. The objective is evaluated
using Cholesky decompositions, so \log |V_i| is computed from the
Cholesky diagonal and quadratic forms are computed by triangular solves
rather than by explicitly inverting V_i. The main likelihood paths pass
analytic gradients to optim(), and the fitted Hessian is retained for
downstream uncertainty calculations when available. The tol argument
is forwarded to the L-BFGS-B factr control; smaller values request
tighter convergence.
Value
With lasso=TRUE, a mars_lasso() object. Otherwise, a list with
class "mars". Common ordinary-model components include:
-
data: analysis data after the selected missing-data handling. -
formula,study_id,outcome_name, andstructure: stored model specification. -
beta_randvarcov_beta: fixed-effect estimates and their estimated covariance matrix. -
est_values: estimated heterogeneity, covariance, or scale-location parameters. -
fit_stats: model-fit statistics such as deviance, AIC, BIC, and related criteria when available. -
QE: sampling-weighted common-effect homogeneity statistic. Multivariate fits additionally storeQE$components(separate marginal outcome tests) andQE$joint_contributions(signed, additive outcome allocations of joint Q, with no separate tests). Marginal tests do not generally sum to joint Q for correlated outcomes. These data frames can be exported withutils::write.csv(). -
residuals,fitted_values,relative_weights, and heterogeneity summaries used by diagnostics and plotting helpers.
The exact component set varies by analysis path because univariate, multivariate and multilevel fits retain different intermediate matrices for downstream diagnostics and summaries.
References
Harville, D. A. (1977). Maximum likelihood approaches to variance component estimation and to related problems. Journal of the American Statistical Association, 72(358), 320–338. doi:10.1080/01621459.1977.10480998.
Patterson, H. D., and Thompson, R. (1971). Recovery of inter-block information when block sizes are unequal. Biometrika, 58(3), 545–554. doi:10.1093/biomet/58.3.545.
Viechtbauer, W. (2005). Bias and efficiency of meta-analytic variance estimators in the random-effects model. Journal of Educational and Behavioral Statistics, 30(3), 261–293. doi:10.3102/10769986030003261.
Dempster, A. P., Laird, N. M., and Rubin, D. B. (1977). Maximum likelihood from incomplete data via the EM algorithm. Journal of the Royal Statistical Society: Series B (Methodological), 39(1), 1–22. doi:10.1111/j.2517-6161.1977.tb01600.x.
Sidik, K., and Jonkman, J. N. (2007). A comparison of heterogeneity variance estimators in combining results of studies. Statistics in Medicine, 26(9), 1964–1981. doi:10.1002/sim.2688.
See Also
mars_lasso() for a dedicated penalized meta-regression interface
with unpenalized baselines and grouped cross-validation.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
summary(fit)
mv_fit <- mars(
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"
)
)
summary(mv_fit)
ml_fit <- mars(
data = school,
formula = effect ~ 1 + (1 | district/study),
studyID = "district",
effectID = NULL,
sample_size = NULL,
variance = "var",
varcov_type = "multilevel",
structure = "multilevel",
estimation_method = "MLE"
)
summary(ml_fit)
Primary main alternative estimation function
Description
Primary main alternative estimation function
Usage
mars_alt_estimation(type = c("bootstrap", "jackknife", "permutation"), ...)
Arguments
type |
Type of alternative estimation to use. |
... |
Additional function arguments passed to each individual alternative functions. |
Examples
alt <- mars_alt_estimation(
type = "jackknife",
data = teacher_expectancy,
structure = "univariate",
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate"
)
summary(alt)
Bivariate meta-analysis of diagnostic test accuracy
Description
Fit a Gaussian or binomial bivariate random-effects model for logit sensitivity and logit specificity from one 2-by-2 table per independent study.
Usage
mars_dta(
data,
studyID,
tp = "TP",
fn = "FN",
fp = "FP",
tn = "TN",
moderators = NULL,
estimation_method = c("REML", "MLE"),
structure = c("UN", "DIAG1"),
zero_cell = c("add_half", "none"),
missing = c("fail", "omit"),
control = list(),
family = c("gaussian", "binomial"),
quadrature = 11L
)
Arguments
data |
Data frame with one row per study for a single index test. |
studyID |
Name of the study identifier column. |
tp, fn, fp, tn |
Names of the true-positive, false-negative, false-positive, and true-negative count columns, respectively. |
moderators |
Optional one-sided formula of study-level predictors. Each endpoint has its own intercept and moderator coefficients. |
estimation_method |
Restricted maximum likelihood ( |
structure |
Between-study covariance structure. Use |
zero_cell |
For Gaussian fits, use |
missing |
Use |
control |
Named list of optimizer controls passed to |
family |
Sampling model. |
quadrature |
Number of adaptive Gauss–Hermite nodes per dimension for binomial fits, an integer from 3 to 35. Increase from the default of 11 to check numerical stability if counts or heterogeneity are extreme. |
Details
Sensitivity uses TP and FN, and specificity uses TN and FP. Both strata
must have positive totals. For Gaussian fits, compute_es() calculates the
two logit proportions and their approximate variances. Conditional on the
stratum totals, their within-study sampling covariance is zero. For
binomial fits, TP and TN have conditionally independent binomial likelihoods
given the study's random effects. A zero cell is valid as long as both
successes and failures are observed for each endpoint across the included
studies. Both models allow true logit values to covary across studies.
A threshold may be a study-level moderator when each study contributes one table. Multiple tests or thresholds measured within a study require additional modeling of their dependence.
Value
A mars_dta object containing the underlying mars fit or binomial
optimizer result (fit),
original tables (counts), endpoint-level analysis data (effects),
labeled logit-scale heterogeneity covariance (tau), and omitted study
IDs (omitted_studies). The effects include raw counts and a continuity
correction flag for each endpoint. Gaussian effects also include yi
and vi. For binomial fits, fit$log_likelihood includes the binomial
normalizing constants.
References
Reitsma, J. B., et al. (2005). Bivariate analysis of sensitivity and specificity produces informative summary measures in diagnostic reviews. Journal of Clinical Epidemiology, 58(10), 982–990. doi:10.1016/j.jclinepi.2005.02.022
Chu, H., and Cole, S. R. (2006). Bivariate meta-analysis of sensitivity and specificity with sparse data: a generalized linear mixed model approach. Journal of Clinical Epidemiology, 59(12), 1331–1332. doi:10.1016/j.jclinepi.2006.06.011
Rutter, C. M., and Gatsonis, C. A. (2001). A hierarchical regression approach to meta-analysis of diagnostic test accuracy evaluations. Statistics in Medicine, 20(19), 2865–2884. doi:10.1002/sim.942.
Harbord, R. M., Deeks, J. J., Egger, M., Whiting, P., and Sterne, J. A. C. (2007). A unification of models for meta-analysis of diagnostic accuracy studies. Biostatistics, 8(2), 239–251. doi:10.1093/biostatistics/kxl004.
See Also
dta_sroc(), predict.mars_dta(), compute_es(), mars()
Examples
counts <- data.frame(study = 1:8, TP = c(44, 50, 56, 59, 64, 68, 69, 71),
TN = c(52, 42, 62, 74, 53, 65, 59, 72))
counts <- transform(counts, FN = 80 - TP, FP = 90 - TN)
fit <- mars_dta(counts, studyID = "study")
predict(fit)
Pool diagnostic accuracy for two paired tests
Description
Fit a Gaussian or multinomial random-effects model for the sensitivity and specificity of two tests applied to the same participants in each study.
Usage
mars_dta_paired(
data,
studyID = "study_id",
stratum = "stratum",
pp = "pp",
pn = "pn",
np = "np",
nn = "nn",
tests = c("test1", "test2"),
zero_cell = c("none", "add_half"),
estimation_method = c("REML", "MLE"),
structure = c("UN", "DIAG1"),
control = list(),
family = c("gaussian", "multinomial"),
quadrature = 11L
)
Arguments
data |
Data frame with two rows per study, one for each reference-standard stratum. |
studyID, stratum |
Names of the study identifier and stratum columns.
Strata must be labeled |
pp, pn, np, nn |
Names of the joint count columns. The letters indicate
positive ( |
tests |
Two distinct test labels, in the order used by the count columns. |
zero_cell |
Use |
estimation_method |
Restricted maximum likelihood ( |
structure |
Between-study covariance structure. Use |
control |
Named optimizer controls passed to |
family |
Sampling model, either |
quadrature |
Number of adaptive Gauss–Hermite nodes per dimension for multinomial fits, an integer from 3 to 35. |
Details
The Gaussian model uses dta_paired_effects() to construct four study-level
logits and their sampling covariance. Both tests must be represented in
every study. At least two studies are required. Both heterogeneity
structures use the full paired sampling covariance. The Gaussian
engine needs invertible sampling blocks. Singular or numerically
singular blocks, such as those from perfectly concordant tests within a
stratum, raise an error identifying the affected studies.
The multinomial model uses the raw four-cell tables and requires
zero_cell = "none". Within each stratum, the log-linear model has
one main effect per test and a fixed interaction. A common normal
study effect shifts both test main effects in that stratum. The study
effects can covary across strata. The interaction is the log odds
ratio of association between the two test results, shared across
studies within that stratum. Empty cells are valid within individual
studies, with each joint outcome observed somewhere in each stratum.
Value
A mars_dta_paired object containing the underlying Gaussian
mars fit (fit), the prepared effects, joint_counts and
sampling_covariance, the correction policy (zero_cell), test labels
(tests), and the labeled between-study covariance (tau).
Multinomial fits contain the optimizer result in fit, raw
joint_counts, stratum-specific association odds ratios
(association), and the between-study covariance of the two common
shifts (tau).
References
Nikoloulopoulos, A. K. (2024). Joint meta-analysis of two diagnostic tests accounting for within and between studies dependence. Statistical Methods in Medical Research, 33(10), 1800–1817. doi:10.1177/09622802241269645.
See Also
summary.mars_dta_paired(), dta_paired_effects()
Examples
i <- seq_len(24)
make_stratum <- function(stratum, p_a, p_b) {
# Mix independent and concordant positive results in these fictional data.
both <- .7 * p_a * p_b + .3 * pmin(p_a, p_b)
pp <- round(200 * both)
pn <- round(200 * (p_a - both))
np <- round(200 * (p_b - both))
data.frame(study_id = sprintf("s%02d", i), stratum, pp, pn, np,
nn = 200 - pp - pn - np)
}
paired_studies <- rbind(
make_stratum("diseased", plogis(1 + .8 * sin(i)),
plogis(1.4 + .5 * sin(i) + .7 * cos(2 * i))),
make_stratum("non_diseased", plogis(-1.1 + .65 * cos(i)),
plogis(-.8 + .45 * cos(i) + .65 * sin(2 * i)))
)
paired_fit <- mars_dta_paired(paired_studies, tests = c("A", "B"))
summary(paired_fit)$contrasts
Pool diagnostic accuracy at reported thresholds
Description
Fit a Gaussian or multinomial random-effects model for the sensitivity and specificity of one test evaluated at multiple cutoffs.
Usage
mars_dta_thresholds(
data,
studyID = "study_id",
threshold = "threshold",
tp = "TP",
fn = "FN",
fp = "FP",
tn = "TN",
positive = c("higher", "lower"),
zero_cell = c("none", "add_half"),
estimation_method = c("REML", "MLE"),
structure = c("DIAG1", "UN"),
control = list(),
family = c("gaussian", "multinomial"),
quadrature = 11L
)
Arguments
data |
Data frame with one row per study and reported cutoff. Both reference-standard strata must be represented at each cutoff. |
studyID, threshold |
Names of the study identifier and numeric cutoff columns. Use comparable cutoffs on the same scale across studies. |
tp, fn, fp, tn |
Names of the true-positive, false-negative, false-positive, and true-negative count columns. Counts must be finite nonnegative integers, with constant positive stratum totals across cutoffs within each study. |
positive |
Use |
zero_cell |
Use |
estimation_method |
Restricted maximum likelihood ( |
structure |
Between-study covariance. The default |
control |
Named optimizer controls passed to |
family |
Sampling model, either |
quadrature |
Number of adaptive Gauss–Hermite nodes per dimension for multinomial fits, an integer from 3 to 35. |
Details
Supply at least two distinct cutoffs overall. Studies may report
different subsets. Gaussian fits require at least two studies per
cutoff. For Gaussian "UN",
each pair of cutoffs must be reported together in at least one study.
Each study's sampling block must be invertible. The fitting function
identifies affected studies when a block is singular or nearly singular.
Gaussian fits estimate separate means at each observed cutoff. Their ordering is unconstrained, so the estimates can be nonmonotone.
Multinomial fits use the raw score bins, with one logistic distribution
per reference-standard stratum. Each stratum has its own mean location
and scale, with normally distributed study-level location effects.
The within-study likelihood integrates the product of the two
multinomial probabilities over these effects. Empty bins are valid and
zero_cell must be "none". The scales are shared across studies
within each stratum. For numerical optimization, log scales in
standardized cutoff units are bounded between -12 and 12.
Value
A mars_dta_thresholds object containing the underlying mars
fit (fit), labeled between-study covariance (tau), and all
components returned by dta_threshold_effects() for Gaussian fits.
Multinomial fits contain the optimizer result in fit, the raw
score_bins, cutoffs, and a parameters table with fitted locations
and scales. The multinomial tau measures between-study location
covariance in squared score units.
References
Hamza, T. H., et al. (2009). Multivariate random effects meta-analysis of diagnostic tests with multiple thresholds. BMC Medical Research Methodology, 9, 73. doi:10.1186/1471-2288-9-73
Jones, H. E., Gatsonis, C. A., Trikalinos, T. A., Welton, N. J., and Ades, A. E. (2019). Quantifying how diagnostic test accuracy depends on threshold in a meta-analysis. Statistics in Medicine, 38(24), 4789–4803. doi:10.1002/sim.8301.
See Also
summary.mars_dta_thresholds(), dta_sroc()
Examples
i <- seq_len(24)
threshold_studies <- do.call(rbind, lapply(0:2, function(cutoff) {
TP <- round(200 * plogis(1.6 - .9 * cutoff + .65 * sin(i) + .15 * cutoff * cos(2 * i)))
FP <- round(200 * plogis(.2 - 1.05 * cutoff + .55 * cos(i) + .15 * cutoff * sin(2 * i)))
data.frame(study_id = sprintf("s%02d", i), threshold = cutoff,
TP = TP, FN = 200 - TP, FP = FP, TN = 200 - FP)
}))
fit <- mars_dta_thresholds(threshold_studies)
summary(fit)$pooled
Coefficient inference options in mars
Description
Summary-time choices select inference for mean coefficients without changing
estimates, variance components or the original fit. Use matching options in
confint() to obtain the same ordinary or network coefficient intervals.
Details
Ordinary mars() fits support normal model inference and cluster-robust
inference with explicit covariance and df choices. Standard and modified HKSJ
are restricted to independent univariate ML/REML fits with estimated constant
heterogeneity and inverse-variance GLS weights. Model test='t' uses n-p df
without rescaling covariance. HKSJ rescales covariance by Q_{\mathrm{res}}/(n-p).
hksj_adjust='modified' uses \max(1,Q_{\mathrm{res}}/(n-p)).
Model-based test='Satterthwaite' uses expected covariance-parameter
information, not the inverse joint observed Hessian. For ML this information
is I_{ab}=\mathrm{tr}(WD_a WD_b)/2. For REML, replace W by
P=W-WX(X'WX)^{-1}X'W. Here D_a denotes a derivative of the total
observation covariance. For contrast variance v and its covariance-parameter
gradient g, \mathrm{df}=2v^2/(g'I^{-1}g). Covariance derivatives for ordinary
fits are evaluated numerically in the fitted covariance coordinates;
network and repeated-effects models use their analytic variance kernels.
Singular information and variance boundaries produce errors, not repaired
or substituted approximations. Scale models are excluded from these overrides.
Cluster-robust Satterthwaite is a different calculation using cluster
influence contributions and the selected sandwich adjustment. CR2 and
CR3 must be estimable; summary overrides do not silently fall back.
Use cluster only for independent units that contain all dependent rows.
A stored robust fit supplies its existing cluster and covariance type.
network_meta_coherent() and mars_repeated() summaries support model
normal/Satterthwaite and robust inference, but not HKSJ or residual-df model t.
Network overrides update only basic coefficients and total treatment
contrasts (including the fitted p-value adjustment). Direct/indirect tests,
diagnostic tests, rankings and predictions retain their fitted calculations.
masmr() stage summaries and hsmd() underlying models inherit ordinary
options; stored MASMR substantive joint tests and benchmark uncertainty
are not recalculated. Selection models, penalized models, forests and
downstream path/factor models do not support these coefficient overrides.
Summary options do not launch bootstrap, jackknife or permutation fitting.
Use mars_alt_estimation() or explicit replicate functions and summarize
their returned results. Jackknife omission ranges remain sensitivity
descriptions rather than sampling confidence intervals.
Model compatibility
The table concerns explicit summary-time overrides, not every inference method available when fitting a model. Yes means supported subject to the requirements below; it does not guarantee estimability for every dataset.
| Model/workflow | Model z | Model t | HKSJ | Model Satterthwaite | Robust tests |
| Independent univariate | Yes | Yes | Yes | Yes | Yes |
| Dependent univariate | Yes | No | No | If covariance is reconstructible | Yes |
| Multivariate/correlation synthesis | Yes | No | No | Yes | Yes |
| Multilevel | Yes | No | No | Yes | Yes |
| Location-scale | Yes | No | No | No | No summary override |
| Coherent network, including repeated networks | Yes | No | No | Yes | Yes |
| Repeated-effects (mars_repeated) | Yes | No | No | Common heterogeneity only | Yes |
| MASMR / HSMD | Inherit | Inherit | Inherit | Inherit | Inherit |
| Selection, LASSO, forest, downstream path/factor | No override | No | No | No | No override |
Model t requires one observation per study, a full-rank mean design and positive n-p residual df. HKSJ additionally requires ML/REML-estimated constant heterogeneity and matched inverse-variance GLS covariance; it excludes common-effect and user-fixed tau2 fits. A zero estimated variance does not itself exclude HKSJ.
Model-based Satterthwaite requires estimated, interior, identifiable heterogeneity and conditional GLS covariance. Common-effect/none and user-fixed heterogeneity, active variance boundaries, nonconvergence and singular covariance information are excluded. Ordinary fits must retain their sampling covariance, outcome indices, design and covariance parameters. Correlation synthesis means inference on fitted pooled coefficients, not automatic Satterthwaite tests for a subsequent path or factor model.
Robust overrides require retained aligned design, residuals and covariance, independent clusters, an estimable sandwich adjustment and positive df. These conditions also apply to common-effect or user-fixed-heterogeneity fits: retaining a model class alone is not enough. An explicit cluster cannot split observations that are dependent in the working covariance. Location-scale fits retain their usual summaries, including stored robust results where available; selecting a new robust summary override is unsupported. MASMR and HSMD check each underlying fitted model separately.
Argument combinations
- inference
Use model for model covariance or robust for sandwich inference. Ordinary summary defaults retain the existing tables; explicit selections return one selected coefficient table.
- test
Model z is normal Wald inference. Model t is restricted to eligible independent univariate fits. Model Satterthwaite uses expected covariance-parameter information; robust Satterthwaite uses cluster influences. Robust z, naive-t (clusters minus one df) and naive-tp (clusters minus coefficients df) are available; robust t aliases naive-t. HKSJ/knha is model-only and follows the compatibility table.
- vcov_method
Ordinary summary/confint model-covariance selection: gls or observed. Observed requires a valid interior ML fit. HKSJ and model Satterthwaite require gls. Do not combine vcov_method with robust inference. Network and repeated-effects summaries do not accept it.
- robust_type and cluster
For robust inference only. Covariance types are CR0, CR1, CR1p, CR1S, CR2 and CR3. An ordinary fit uses its stored robust type/cluster when available; otherwise supply cluster, and the covariance defaults to CR2. Networks and repeated-effects models default to study clustering. A network fit already using CR1 retains CR1 and naive-t unless explicitly overridden.
- hksj_adjust
Only with model HKSJ for eligible independent univariate fits: standard or modified. Unsupported on network and repeated-effects models; it is not a robust covariance adjustment.
- level
Pointwise coefficient confidence level. Network summaries also update total treatment-contrast confidence intervals. This does not set prediction coverage, simultaneous coverage or resampling coverage.
References
Hedges, L. V., Tipton, E., and Johnson, M. C. (2010). Robust variance estimation in meta-regression with dependent effect size estimates. Research Synthesis Methods, 1(1), 39–65. doi:10.1002/jrsm.5.
Tipton, E. (2015). Small sample adjustments for robust variance estimation with meta-regression. Psychological Methods, 20(3), 375–393. doi:10.1037/met0000011.
Pustejovsky, J. E., and Tipton, E. (2018). Small-sample methods for cluster-robust variance estimation and hypothesis testing in fixed effects models. Journal of Business & Economic Statistics, 36(4), 672–683. doi:10.1080/07350015.2016.1247004.
Sidik, K., and Jonkman, J. N. (2002). A simple confidence interval for meta-analysis. Statistics in Medicine, 21(21), 3153–3159. doi:10.1002/sim.1262.
Knapp, G., and Hartung, J. (2003). Improved tests for a random effects meta-regression with a single covariate. Statistics in Medicine, 22(17), 2693–2710. doi:10.1002/sim.1482.
Röver, C., Knapp, G., and Friede, T. (2015). Hartung-Knapp-Sidik-Jonkman approach and its modification for random-effects meta-analysis with few studies. BMC Medical Research Methodology, 15, 99. doi:10.1186/s12874-015-0091-1.
See Also
summary.mars(), summary.mars_repeated(), network_model_summary
Examples
fit <- mars(school, formula=effect~1, studyID="study", variance="var",
varcov_type="univariate", structure="univariate")
summary(fit, inference="model", test="hksj", hksj_adjust="modified")
summary(fit, inference="model", test="Satterthwaite")
summary(fit, inference="robust", cluster="district", robust_type="CR2",
test="Satterthwaite")
confint(fit, inference="model", test="hksj", hksj_adjust="modified")
Penalized Meta-Regression with Study-Grouped Cross-Validation
Description
Fits univariate, nested multilevel or multivariate meta-regression with an L1 penalty on moderator coefficients and unpenalized mean baselines.
Usage
mars_lasso(
data,
studyID,
formula = NULL,
variance = NULL,
structure = "univariate",
effectID = NULL,
sample_size = NULL,
effectsize_type = NULL,
variable_names = NULL,
effectsize_name = NULL,
varcov_type = NULL,
multivariate_covs = NULL,
outcome_specific = FALSE,
lambda_grid = 10^seq(2, -3, length.out = 20),
folds = 5L,
selection = c("1se", "min", "fixed"),
lambda = NULL,
penalty_factor = NULL,
standardize = TRUE,
heterogeneity = c("estimate", "none"),
prediction_scale = c("fisher_z", "raw"),
missing = c("remove", "em"),
seed = 1L,
maxit = 200L,
tol = 1e-07,
...
)
mars_lasso_univariate(data, formula, studyID, variance, ...)
mars_lasso_multilevel(data, formula, studyID, variance, ...)
mars_lasso_multivariate(data, studyID, effectsize_type, effectID = NULL, ...)
Arguments
data |
Data frame of effect estimates, sampling inputs and moderators. |
studyID |
Column naming independent studies or the outermost multilevel group. |
formula |
Two-sided univariate/multilevel formula. One additive nested random-intercept term is supported for multilevel fits; random slopes and crossed terms are unsupported. Parenthesized predictors and response expressions are preserved. Specify predictors explicitly rather than using a dot formula. |
variance |
Sampling variance column for formula inputs. |
structure |
univariate or multilevel for formula inputs; multivariate is inferred for effect-size inputs. |
effectID |
Effect ID column for long-form SMD inputs. Correlation inputs generate canonical pair IDs and do not require this argument. |
sample_size |
Sample-size column for multivariate inputs. |
effectsize_type |
cor or smd for multivariate inputs. |
variable_names |
Complete pair-named correlation columns for wide input. |
effectsize_name |
Effect estimate column for long-form SMD input. |
varcov_type |
Sampling-covariance type. Defaults to univariate/multilevel for formula inputs and weighted for correlations. Specify a valid SMD type explicitly. Sampling covariance must be positive definite. |
multivariate_covs |
Explicit one-sided moderator formula for multivariate input. |
outcome_specific |
FALSE fits common moderator slopes across outcomes; TRUE fits separate penalized slopes by outcome, retaining unpenalized baselines. |
lambda_grid |
Distinct finite nonnegative penalties. The default grid is fixed in advance, not computed from held-out outcomes. Fits run in descending order with warm starts. Expand the grid if selection reaches an endpoint. |
folds |
Number of study/group cross-validation folds, at least three and no greater than independent groups. Each training fold refits all preprocessing and variance components. Use NULL with selection='fixed' to skip tuning. |
selection |
min minimizes mean held-out Gaussian negative log likelihood; 1se chooses the largest penalty within one fold-score standard error of the minimum. Exact min-score ties prefer the largest lambda. fixed uses lambda directly and skips cross-validation. |
lambda |
Explicit penalty with selection='fixed'. |
penalty_factor |
Optional nonnegative weights for fixed design columns, preferably named. Unspecified moderator weights are one; baseline weights are always zero. No rescaling of penalty factors is performed. |
standardize |
TRUE centers and scales nonbaseline design columns using training-fold sample standard deviations. Encoded categorical contrasts and interaction columns are scaled individually. Baselines remain unscaled; no centering occurs in an explicitly intercept-free formula. |
heterogeneity |
estimate fits nonnegative ML variance components; none fixes all components at zero, yielding penalized sampling-covariance GLS. |
prediction_scale |
Correlation fits use fisher_z by default, with |
missing |
remove drops incomplete required records (whole matrices for wide correlation input); em supports training-fold continuous-moderator completion. Entirely missing or categorical incomplete EM moderators are unsupported. Imputation uncertainty is not propagated. |
seed |
Fold assignment seed; the caller's RNG state is restored. |
maxit |
Maximum alternating mean/covariance iterations per start. |
tol |
Positive numerical convergence tolerance. |
... |
Unsupported arguments are rejected. |
Details
For G independent groups, the optimized criterion is
[\sum_g \{\log|V_g|+(y_g-X_g\beta)^T V_g^{-1}(y_g-X_g\beta)\}]/(2G)
+ \lambda \sum_j a_j |\beta_j|.
Penalties apply on the standardized design scale; reported coefficients are
restored to the supplied design units. Transformed predictors retain their
transformation units. Intercepts and multivariate outcome baselines have
a_j=0. Categorical contrasts are penalized individually, not as a group, so
selection can depend on contrast coding. A zero coefficient is a numerical
LASSO selection result, not evidence of a zero causal or population effect.
Sampling covariance is represented in every block. Univariate heterogeneity adds an independent effect-level variance; nested multilevel models add random-intercept covariance; multivariate models use diagonal between-study heterogeneity by outcome. They do not estimate an unstructured between-outcome heterogeneity matrix. REML, scale formulas, random slopes and post-selection robust/Wald inference are outside this interface.
Coordinate descent solves the mean LASSO problem conditional on covariance;
bounded ML optimization updates variance components. Stationarity diagnostics
and multiple deterministic starts are used because joint variance estimation
is nonconvex. Final KKT residuals must not exceed \max(10^{-5},\sqrt{\mathrm{tol}});
coordinate updates use tol directly. Convergence does not prove a global
optimum. Failed paths or
folds are diagnosed, not assigned fabricated scores; a lambda is eligible for
selection only when every fold succeeds and its full-data fit converges.
Validation predicts population means for new groups and uses training
covariance estimates plus held-out sampling covariance. Correlation pooled
covariance is learned from training matrices and transferred to held-out
sample sizes. Each group contributes its whole multivariate log-density score;
larger blocks can contribute more. The 1se rule uses the standard deviation
of fold mean scores divided by \sqrt{K}, an approximate tuning rule rather
than a confidence interval. Tuning-fold results are not an independent final
performance evaluation; use an outer grouped validation loop for that purpose.
Unknown categorical levels/outcomes fail prediction and are reported in CV
diagnostics. Coefficients are mean-model coefficients, not BLUPs.
With pooled correlation covariance, held-out Fisher-z derivatives use training
pooled correlations; simple sampling covariance uses supplied held-out study
sampling inputs. Correlation prediction supports explicit complete-matrix
checks and repair; bounded pairs
alone do not guarantee a positive-semidefinite matrix.
The main mars() interface with lasso=TRUE delegates to this same engine
and returns this same class. Place tuning controls in its lasso_args list;
folds can also be named K. Both routes share defaults and produce identical
estimates, paths, CV scores and predictions for matched inputs. Call records
may differ. Explicit estimation_method in mars() must be MLE, and an explicit
multivariate structure must be multivariate or DIAG1. See mars() for
unsupported ordinary-fitting arguments and argument mapping.
Value
A mars_lasso object containing selected point estimates, lambda, coefficient and variance-component paths, convergence diagnostics, training preprocessing, fold assignments, group-level validation scores and CV summary. Ordinary Wald standard errors, p-values and confidence intervals are not returned for selected coefficients. These require selection-aware inference.
References
Tibshirani, R. (1996). Regression shrinkage and selection via the lasso. Journal of the Royal Statistical Society: Series B (Methodological), 58(1), 267–288. doi:10.1111/j.2517-6161.1996.tb02080.x.
Friedman, J. H., Hastie, T., and Tibshirani, R. (2010). Regularization paths for generalized linear models via coordinate descent. Journal of Statistical Software, 33(1), 1–22. doi:10.18637/jss.v033.i01.
Examples
fit <- mars_lasso_univariate(teacher_expectancy, yi ~ year + weeks,
"study", "vi", lambda_grid=c(10,1,.1), folds=3, seed=1)
coef(fit)
# The general interface also accepts a fixed penalty.
general <- mars_lasso(teacher_expectancy, "study", yi ~ year + weeks, "vi",
selection = "fixed", lambda = .1)
coef(general)
x <- seq(-2, 2, length.out = 24)
nested <- data.frame(district = rep(1:8, each = 3), study = 1:24,
x = x, y = 2 + .6 * x + .05 * sin(1:24), vi = .05)
multilevel <- mars_lasso_multilevel(nested, y ~ x + (1 | district/study),
"district", "vi",
lambda_grid = c(1, .1), folds = 3)
coef(multilevel)
i <- 1:12
correlations <- data.frame(study = i, n = seq(60, 170, 10), z = i,
b_a = .1 + .01 * i, c_a = .2 + .01 * i,
c_b = .3 + .01 * i)
multivariate <- mars_lasso_multivariate(
correlations, "study", "cor", sample_size = "n",
variable_names = c("b_a", "c_a", "c_b"), multivariate_covs = ~ z,
lambda_grid = c(1, .1), folds = 3
)
coef(multivariate)
Repeated-effects multivariate meta-analysis
Description
Synthesizes dependent effect sizes from studies reporting multiple outcomes,
treatment groups, or follow-up times. It constructs study covariance blocks
internally from explicit, user-chosen correlation assumptions and leaves
mars() unchanged.
Usage
mars_repeated(
data,
study_id,
effect,
variance,
outcome_id = NULL,
group_id = NULL,
control_id = NULL,
time_id = NULL,
mean_structure = c("common", "by_outcome", "by_time", "by_group", "by_outcome_time",
"by_outcome_group_time"),
outcome_correlation = c("independence", "exchangeable"),
time_correlation = c("independence", "exchangeable", "ar1"),
rho_outcome = 0,
rho_time = 0,
rho_shared_control = 0,
heterogeneity = c("none", "common"),
estimation_method = c("REML", "ML"),
ci_level = 0.95
)
Arguments
data |
Data frame with one row per effect size. |
study_id, effect, variance |
Character strings naming the study, effect, and marginal sampling-variance columns. |
outcome_id, group_id, control_id, time_id |
Optional character strings identifying outcome, treatment group/contrast, shared control, and time. |
mean_structure |
Mean model: a common effect, or effects stratified by outcome, time, group, outcome-by-time, or outcome-by-group-by-time. |
outcome_correlation |
Correlation for different outcomes from the same
group. Choose |
time_correlation |
Correlation for different times from the same group.
Choose |
rho_outcome, rho_time |
Assumed correlations for the selected outcome and time structures. Values must be between minus one and one. |
rho_shared_control |
Assumed correlation for effects from different groups with the same control identifier. |
heterogeneity |
Either |
estimation_method |
Either |
ci_level |
Confidence level for mean-effect intervals. |
Details
The covariance is a separable working model. For two effects in the
same study, dependence is nonzero only when they share a group or a supplied
control identifier. Within-group dependence is the product of outcome and
time correlations. Different groups sharing a control receive the additional
rho_shared_control factor. The function uses a near-positive-semidefinite
adjustment when needed and records whether it was applied. This is a useful,
transparent working covariance model when full study covariance matrices are
unavailable; it is not a substitute for reported correlations or raw data.
Value
An object of class mars_repeated with coefficient summaries,
internally constructed sampling covariance blocks, and recorded covariance
assumptions.
Examples
dat <- data.frame(
study = rep(c("S1", "S2", "S3"), each = 2),
yi = c(.2, .3, .1, .25, .4, .5), vi = .04,
outcome = rep(c("pain", "function"), 3)
)
mars_repeated(dat, "study", "yi", "vi", outcome_id = "outcome",
outcome_correlation = "exchangeable", rho_outcome = .5)
Random Forest Meta-Analysis Models
Description
Fits a study-bootstrap random forest for meta-analytic data without modifying
the core estimation() pipeline. The function borrows the same data
preparation patterns used in mars for univariate, multivariate, and
multilevel inputs, then trains a forest-style ensemble of weighted
regression trees with random predictor subsampling.
Usage
mars_rf(
data,
studyID,
effectID = NULL,
sample_size = NULL,
effectsize_type = NULL,
formula = NULL,
variable_names = NULL,
effectsize_name = NULL,
variance = NULL,
varcov_type,
structure = "univariate",
intercept = FALSE,
missing = "remove",
multivariate_covs = NULL,
num_trees = 500L,
mtry = NULL,
minsplit = 10L,
minbucket = 5L,
cp = 0.001,
maxdepth = 30L,
sample_fraction = 1,
seed = NULL,
importance = TRUE,
weighting = c("sampling", "uniform", "random"),
selection = c("node", "tree"),
min_studies = 2L,
prediction_scale = c("fisher_z", "raw"),
...
)
Arguments
data |
Data used for analysis. |
studyID |
Character string representing the study ID. |
effectID |
Effect ID column for long-form SMD inputs. Correlation inputs generate canonical pair identities from variable_names and expose them as numID. |
sample_size |
Character string representing study sample size. |
effectsize_type |
Type of effect size being analyzed, such as |
formula |
Predictor formula for univariate models. Multilevel models
additionally require one nested random-intercept term, such as
|
variable_names |
Vector of variables used for correlation synthesis in multivariate models. |
effectsize_name |
Character string naming the effect size column. |
variance |
Character string naming the variance column for formula-based fits. |
varcov_type |
Type of within-study sampling covariance. Correlation
forests require raw-correlation |
structure |
Structure label. Use |
intercept |
Coding option for the stored multivariate design matrix. Terminal prediction models always include a baseline. |
missing |
Missing-data handling mode. Use |
multivariate_covs |
One-sided formula specifying moderator covariates for multivariate models. |
num_trees |
Number of trees in the forest. |
mtry |
Number of candidate moderators selected at each node (default) or
once per tree. Defaults to |
minsplit, minbucket |
Tree-growing control parameters. |
cp |
Nonnegative fraction of the root weighted squared error required for a split. The same absolute penalty is used for cost-complexity pruning. |
maxdepth |
Maximum tree depth. |
sample_fraction |
Fraction of studies sampled with replacement for each tree. |
seed |
Optional random seed; the caller's RNG state is restored afterward. |
importance |
Logical; if |
weighting |
Split-loss weights: |
selection |
|
min_studies |
Minimum distinct original resampling groups in each child node and for leaf variance estimation (which also requires at least two). Bootstrap copies do not count as additional independent groups. |
prediction_scale |
Correlation-only fitting scale: |
... |
Additional arguments are rejected. |
Details
All three paths use one additive weighted squared error criterion for growing and pruning trees. Terminal leaves in multivariate and multilevel forests are subsequently refined with GLS or profiled marginal ML fits. Within-study covariance and random effects enter leaf fitting, not the split criterion. The forest is an exploratory predictor, not a joint likelihood model for all leaves.
mars_rf() currently supports three analysis paths:
Univariate: weighted tree ensembles using study-level resampling and explicitly selected split-loss weights.
Multivariate: weighted trees with terminal ML models for outcome-specific heterogeneity and within-study sampling covariance.
Multilevel: weighted trees with nested-group bootstrap sampling and terminal random-intercept ML models. Child IDs are nested within their ancestors, so reused labels in different parents remain distinct.
Bootstrap multiplicities are retained as independent copies of entire study blocks. Correlation covariance pooling is repeated within each tree's training sample. Variance components are fitted only to in-bag observations. OOB predictions therefore exclude the held-out outcomes from tree fitting, but remain conditional on the prepared predictor representation. Use external grouped validation when preprocessing or tuning must also be validated.
Terminal ML minimizes \log|V| + (y-Xb)^T V^{-1}(y-Xb), profiling
b by GLS and constraining variance components to be nonnegative.
Nonconvergence, insufficient residual degrees of freedom, or indistinguishable
variance components trigger an explicitly diagnosed sampling-covariance GLS
fit. These likelihood values are never compared to choose tree splits.
Known groups receive leaf BLUPs; unknown or omitted group IDs receive zero
random-effect contributions. Predictor transformations are frozen at training.
Split importance averages retained weighted-error reductions over trees and
does not measure the additional contribution of terminal linear coefficients.
The function is intended for exploratory moderator detection, nonlinear
pattern discovery, and structure-aware prediction inside meta-analytic data.
Users who need the exact likelihood-based estimators reported by the core
package should continue to use mars() for confirmatory model fitting.
Prediction accepts type = "response", "working" or "matrix".
Multilevel re_form = "population" omits all BLUPs; "conditional" uses
known groups where available. For complete correlation predictions, provide
the internal study and effect columns (see study_id and effect_id).
matrix_action = "warn" checks bounds and positive semidefiniteness;
"error" rejects invalid matrices; "none" skips checks. Explicit
"repair" uses Matrix::nearPD on complete matrices and records minimum
eigenvalues and maximum changes. Fisher-z bounds alone do not guarantee a valid
joint correlation matrix. Incomplete predictions cannot be repaired.
Multivariate ML leaves assume diagonal between-study heterogeneity by outcome;
sampling-error covariance remains fully represented. Leaf-specific likelihoods
do not define a single joint likelihood across the ensemble. Split importance
does not include terminal linear prediction. OOB errors and grouped validation
metrics use inverse raw sampling variances on the response scale, independent
of the split weighting option. Use mars_rf_validate() for complete grouped
validation and rf_importance() for held-out permutation importance. Tuning
against those results requires an additional outer validation loop.
Formulas are parsed structurally. Parentheses retain ordinary predictors;
response expressions are evaluated in data; explicit interactions also enter
terminal linear models. Outcomes cannot be moderators. Specify moderators
explicitly rather than using dot formulas. Correlation moderator names that
conflict with generated fields are rejected with instructions to rename them.
missing = "remove" removes rows with missing required outcomes, variances
or moderators (whole matrices for wide correlation inputs); nonmissing invalid
variances are errors. "keep" only permits missing predictors, not targets or
covariance inputs. EM completes continuous moderators; future rows use the
training conditional-normal moments. Entirely missing categorical predictors
under keep are treated as constant predictors.
Value
A list of class "mars_rf" containing the fitted forest, fitted and
OOB predictions, variable importance, preprocessed data, and
fit_diagnostics for terminal fits. Each tree records sampled units,
their draw counts and its root variance estimates. random_tau is
the componentwise median of multilevel tree-root estimates, not a
confirmatory full-data variance estimate. Unsupported root fits are excluded;
a component with no successful root fits is NA. Outcome-specific OOB metrics
are returned in oob_by_effect. The stored refit_args permit grouped validation.
References
Breiman, L. (2001). Random forests. Machine Learning, 45, 5–32. doi:10.1023/A:1010933404324.
van Lissa, C. J. (2020). Small sample meta-analyses: Exploring heterogeneity using MetaForest. In R. van de Schoot and M. Miočević (Eds.), Small Sample Size Solutions: A Guide for Applied Researchers and Practitioners (pp. 186–202). Routledge. doi:10.4324/9780429273872-16.
Examples
rf_uni <- mars_rf(
data = teacher_expectancy,
formula = yi ~ year + weeks + factor(setting) + factor(tester),
studyID = "study",
variance = "vi",
varcov_type = "univariate",
structure = "univariate",
num_trees = 25,
seed = 123
)
summary(rf_uni)
rf_multi <- mars_rf(
data = becker09,
studyID = "ID",
sample_size = "N",
effectID = "numID",
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 = 25,
seed = 123
)
head(rf_importance(rf_multi))
Multilevel Random Forest Meta-Analysis
Description
Convenience wrapper around mars_rf() for formula-based multilevel models.
Usage
mars_rf_multilevel(
data,
formula,
studyID,
variance,
structure = NULL,
varcov_type = "multilevel",
missing = "remove",
num_trees = 500L,
mtry = NULL,
minsplit = 10L,
minbucket = 5L,
cp = 0.001,
maxdepth = 30L,
sample_fraction = 1,
seed = NULL,
importance = TRUE,
weighting = c("sampling", "uniform", "random"),
selection = c("node", "tree"),
min_studies = 2L,
prediction_scale = c("fisher_z", "raw"),
...
)
Arguments
data |
Data used for analysis. |
formula |
Predictor formula for univariate models. Multilevel models
additionally require one nested random-intercept term, such as
|
studyID |
Character string representing the study ID. |
variance |
Character string naming the variance column for formula-based fits. |
structure |
Structure label. Use |
varcov_type |
Type of within-study sampling covariance. Correlation
forests require raw-correlation |
missing |
Missing-data handling mode. Use |
num_trees |
Number of trees in the forest. |
mtry |
Number of candidate moderators selected at each node (default) or
once per tree. Defaults to |
minsplit, minbucket |
Tree-growing control parameters. |
cp |
Nonnegative fraction of the root weighted squared error required for a split. The same absolute penalty is used for cost-complexity pruning. |
maxdepth |
Maximum tree depth. |
sample_fraction |
Fraction of studies sampled with replacement for each tree. |
seed |
Optional random seed; the caller's RNG state is restored afterward. |
importance |
Logical; if |
weighting |
Split-loss weights: |
selection |
|
min_studies |
Minimum distinct original resampling groups in each child node and for leaf variance estimation (which also requires at least two). Bootstrap copies do not count as additional independent groups. |
prediction_scale |
Correlation-only fitting scale: |
... |
Additional arguments are rejected. |
Examples
rf_fit <- mars_rf_multilevel(
data = teacher_expectancy,
formula = yi ~ year + (1 | study),
studyID = "study",
variance = "vi",
num_trees = 25,
seed = 123
)
summary(rf_fit)
Multivariate Random Forest Meta-Analysis
Description
Convenience wrapper around mars_rf() for multivariate correlation or SMD
inputs.
Usage
mars_rf_multivariate(
data,
studyID,
effectID = NULL,
sample_size = NULL,
effectsize_type,
variable_names = NULL,
effectsize_name = NULL,
varcov_type,
intercept = FALSE,
missing = "remove",
multivariate_covs = NULL,
num_trees = 500L,
mtry = NULL,
minsplit = 10L,
minbucket = 5L,
cp = 0.001,
maxdepth = 30L,
sample_fraction = 1,
seed = NULL,
importance = TRUE,
weighting = c("sampling", "uniform", "random"),
selection = c("node", "tree"),
min_studies = 2L,
prediction_scale = c("fisher_z", "raw"),
...
)
Arguments
data |
Data used for analysis. |
studyID |
Character string representing the study ID. |
effectID |
Effect ID column for long-form SMD inputs. Correlation inputs generate canonical pair identities from variable_names and expose them as numID. |
sample_size |
Character string representing study sample size. |
effectsize_type |
Type of effect size being analyzed, such as |
variable_names |
Vector of variables used for correlation synthesis in multivariate models. |
effectsize_name |
Character string naming the effect size column. |
varcov_type |
Type of within-study sampling covariance. Correlation
forests require raw-correlation |
intercept |
Coding option for the stored multivariate design matrix. Terminal prediction models always include a baseline. |
missing |
Missing-data handling mode. Use |
multivariate_covs |
One-sided formula specifying moderator covariates for multivariate models. |
num_trees |
Number of trees in the forest. |
mtry |
Number of candidate moderators selected at each node (default) or
once per tree. Defaults to |
minsplit, minbucket |
Tree-growing control parameters. |
cp |
Nonnegative fraction of the root weighted squared error required for a split. The same absolute penalty is used for cost-complexity pruning. |
maxdepth |
Maximum tree depth. |
sample_fraction |
Fraction of studies sampled with replacement for each tree. |
seed |
Optional random seed; the caller's RNG state is restored afterward. |
importance |
Logical; if |
weighting |
Split-loss weights: |
selection |
|
min_studies |
Minimum distinct original resampling groups in each child node and for leaf variance estimation (which also requires at least two). Bootstrap copies do not count as additional independent groups. |
prediction_scale |
Correlation-only fitting scale: |
... |
Additional arguments are rejected. |
Examples
rf_fit <- 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 = 25,
seed = 123
)
rf_importance(rf_fit)
Univariate Random Forest Meta-Analysis
Description
Convenience wrapper around mars_rf() for formula-based univariate models.
Usage
mars_rf_univariate(
data,
formula,
studyID,
variance,
structure = NULL,
varcov_type = "univariate",
missing = "remove",
num_trees = 500L,
mtry = NULL,
minsplit = 10L,
minbucket = 5L,
cp = 0.001,
maxdepth = 30L,
sample_fraction = 1,
seed = NULL,
importance = TRUE,
weighting = c("sampling", "uniform", "random"),
selection = c("node", "tree"),
min_studies = 2L,
prediction_scale = c("fisher_z", "raw"),
...
)
Arguments
data |
Data used for analysis. |
formula |
Predictor formula for univariate models. Multilevel models
additionally require one nested random-intercept term, such as
|
studyID |
Character string representing the study ID. |
variance |
Character string naming the variance column for formula-based fits. |
structure |
Structure label. Use |
varcov_type |
Type of within-study sampling covariance. Correlation
forests require raw-correlation |
missing |
Missing-data handling mode. Use |
num_trees |
Number of trees in the forest. |
mtry |
Number of candidate moderators selected at each node (default) or
once per tree. Defaults to |
minsplit, minbucket |
Tree-growing control parameters. |
cp |
Nonnegative fraction of the root weighted squared error required for a split. The same absolute penalty is used for cost-complexity pruning. |
maxdepth |
Maximum tree depth. |
sample_fraction |
Fraction of studies sampled with replacement for each tree. |
seed |
Optional random seed; the caller's RNG state is restored afterward. |
importance |
Logical; if |
weighting |
Split-loss weights: |
selection |
|
min_studies |
Minimum distinct original resampling groups in each child node and for leaf variance estimation (which also requires at least two). Bootstrap copies do not count as additional independent groups. |
prediction_scale |
Correlation-only fitting scale: |
... |
Additional arguments are rejected. |
Examples
rf_fit <- mars_rf_univariate(
data = teacher_expectancy,
formula = yi ~ year + weeks,
studyID = "study",
variance = "vi",
num_trees = 25,
seed = 123
)
summary(rf_fit)
Grouped Validation for Random Forest Meta-Analysis
Description
Refits the complete RF workflow inside folds that hold out whole studies or outermost multilevel groups. Each training fold learns transformations, sampling-covariance pooling, heterogeneity weights and any EM completion.
Usage
mars_rf_validate(object, folds = 5L, seed = 1L, permutation_repeats = 0L)
Arguments
object |
A fitted |
folds |
Number of folds, at least two and no more than independent groups. |
seed |
Reproducible fold assignment and refitting seed. RNG state is restored. |
permutation_repeats |
Number of held-out permutations per moderator; zero skips importance. Study-invariant predictors are permuted between groups as whole blocks. Varying predictors require exchangeable groups of equal size; otherwise their permutation importance is unavailable. |
Details
This evaluates population prediction for new groups. Tuning or selecting moderators with these same folds requires an additional outer validation loop. Errors in a fold are recorded, not replaced with in-sample predictions; pooled metrics use successful folds and report coverage. With EM, held-out continuous predictors are completed using training-fold conditional-normal moments. Missing categorical prediction moderators are unsupported. Coverage counts independent groups represented by successful evaluated rows. Errors predict observed effects rather than latent true effects; studies with greater precision or more observations can contribute more to pooled scores. Multivariate pooled R-squared can reflect different outcome means, so inspect by_effect. Permutations require exchangeable groups and compatible within-group ordering; with EM they act on completed held-out moderators. At least two held-out groups are required. Structural effect identity is not included in permutation importance.
Value
A list with row-level held-out predictions, pooled sampling-variance weighted RMSE and R-squared, outcome-specific metrics, fold diagnostics and permutation importance. Importance is the increase in weighted squared error on held-out data, averaged over repetitions and folds using evaluation weights. Negative values are possible. Results condition on the supplied tuning choices.
Examples
fit <- mars_rf_univariate(teacher_expectancy, yi ~ year + weeks,
"study", "vi", num_trees = 5, seed = 1)
validation <- mars_rf_validate(fit, folds = 3, seed = 2)
validation$metrics
Methodology-Adjusted Substantive Meta-Regression (MASMR)
Description
Fits a methodology-only baseline and a joint meta-regression of the original outcome on methodology and substantive moderators. Substantive associations are estimated in the joint model, conditional on all included predictors.
Usage
masmr(
data,
methodology_mods,
substantive_mods,
formula = NULL,
studyID,
effectID = NULL,
sample_size = NULL,
effectsize_type = NULL,
effectsize_name = NULL,
estimation_method = "REML",
variance = NULL,
varcov_type,
weights = NULL,
structure = "univariate",
intercept = FALSE,
missing = "remove",
optim_method = "L-BFGS-B",
robustID = NULL,
robust_args = list(),
lasso = FALSE,
lasso_args = list(lambda_grid = 10^seq(1, -3, length.out = 5), K = 5, all_lasso_metrics
= FALSE, lambda_tolerance = 0),
tol = 1e+07,
adjusted_effect_name = "yi_masmr",
interactions = NULL,
outcome = NULL,
measure = NULL,
units = NULL,
sampling_covariance = NULL,
...
)
## S3 method for class 'masmr'
summary(object, fit_measures = TRUE, ...)
## S3 method for class 'summary.masmr'
print(x, ...)
Arguments
data |
Data frame used for analysis. |
methodology_mods |
Character vector of methodology moderator terms. |
substantive_mods |
Character vector of substantive moderator terms. |
formula |
Optional formula input for univariate/multilevel analysis. |
studyID |
Study identifier column name. |
effectID |
Effect identifier column name (used for SMD-style workflow). |
sample_size |
Sample-size column name (used for SMD-style workflow). |
effectsize_type |
The non-formula workflow supports "smd". For other measures use formula or outcome-aware precomputed inputs. |
effectsize_name |
Effect-size column name. |
estimation_method |
Estimation method passed to |
variance |
Variance column name. |
varcov_type |
Variance-covariance type passed to |
weights |
Optional user-defined weights. |
structure |
Model structure passed to |
intercept |
Intercept flag passed to |
missing |
Missing-data mode: |
optim_method |
Optimization method passed to |
robustID |
Optional robust clustering ID passed to |
robust_args |
Named list of robust covariance and inference controls passed to both MARS stages. |
lasso |
Must be FALSE; penalized inference is not supported. |
lasso_args |
Unused because LASSO is not supported in MASMR. |
tol |
Optimization tolerance passed to |
adjusted_effect_name |
Unused; MASMR fits the original outcome jointly. Supplying this argument produces a warning. |
interactions |
Optional explicit substantive-by-methodology interaction
terms, for example |
outcome |
Optional column naming outcomes for outcome-aware multivariate fits. Uses outcome-specific intercepts and moderator coefficients. |
measure |
Analysis measure code, or a named code per outcome. OR, RR and
HR denote already log-transformed estimates; ZCOR denotes Fisher z. No
transformation is automatic. See |
units |
Optional units, named per outcome; required for MD. |
sampling_covariance |
Positive-definite sampling covariance in original input row order. Mutually exclusive with weights; heterogeneity is separate. |
... |
Additional arguments passed to printing methods for the stage summaries. |
object |
An object of class |
fit_measures |
Logical; if |
x |
An object of class |
Details
Use masmr_contrast() to compare substantive scenarios under an explicit
methodological profile or shared distribution. Target weights define the
estimand and are distinct from fitting weights. masmr_support() reports
support diagnostics. Existing coefficient summaries retain model-based normal
inference; contrast inference is selected explicitly in the contrast call.
Both models use the
original outcome and sampling covariance; no stage-1 residuals are refitted.
The moderator lists define the fixed predictors; formula supplies the outcome,
intercept convention and random terms. Terms may not overlap between lists.
The substantive table and test use model-based covariance, not robust
covariance. Robust results, when requested, remain available in the joint fit.
Inference is asymptotic and inherits the assumptions of MARS. Use ML, not REML
likelihood comparisons, when comparing different fixed predictor sets.
EM uses the shared MARS multivariate-normal completion helper once before
fitting. Missing predictors must be continuous; incomplete categorical
predictors are rejected. Repeated studies require study-level invariant
predictors. Missing outcomes and variances are not imputed. Complete scale
predictors and moderator variables condition the completion; outcome values
and additional auxiliary variables are not automatically included.
Completed source predictors are held fixed during sensitivity refits.
Support diagnostics describe completed-data geometry, not purely observed
support. EM convergence does not establish the missingness assumptions or
account for imputation uncertainty. Use external proper multiple imputation
and appropriate pooling for uncertainty-aware missing-data inference.
LASSO is not supported. SMD user weights and transformed calls
inside random terms are rejected explicitly. Create transformed random-slope
columns in the data before fitting.
Value
An object of class "masmr" containing:
- baseline, joint
Methodology-only and joint fitted MARS models.
- stage1, stage2
Additional names for baseline and joint.
- analysis_data
Original-outcome analysis data shared by both models.
- missing_data
Missing-data method and EM diagnostics, including original and completed predictors and the missingness mask in original input order. With EM, both fitted models carry the same diagnostics.
- substantive_coefficients
Joint substantive coefficients with model-based normal 95 percent intervals and two-sided p-values.
- substantive_test
Joint model-based Wald chi-square test of all substantive design columns, conditional on methodology.
- workflow
One of
"formula","multivariate", or"smd".
References
Dempster, A. P., Laird, N. M., and Rubin, D. B. (1977). Maximum likelihood from incomplete data via the EM algorithm. Journal of the Royal Statistical Society: Series B (Methodological), 39(1), 1–22. doi:10.1111/j.2517-6161.1977.tb01600.x.
Examples
out <- masmr(
data = teacher_expectancy,
methodology_mods = c("factor(tester)"),
substantive_mods = c("year", "weeks", "factor(setting)"),
formula = yi ~ 1 + year + weeks + factor(setting) + factor(tester),
studyID = "study",
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
summary(out)
Calibrate an interaction bound from two methodological shifts
Description
Calibrate an interaction bound from two methodological shifts
Usage
masmr_bound_difference(term, shift_a, shift_b, divisor = 1, ...)
Arguments
term |
Name of the departure coefficient. |
shift_a, shift_b |
Finite increasing lower/upper ranges for the methodological shift in substantive conditions A and B, in original units. |
divisor |
Positive fixed conversion divisor, e.g. a justified reference
SD. The bounds are |
... |
Metadata passed to |
Value
A bounds object retaining the calibration inputs and formula.
Examples
masmr_bound_difference(
"S:M", shift_a = c(.2, .6), shift_b = c(.6, 1.2), divisor = 10,
meaning = "Assessment-by-group interaction", units = "SMD",
justification = "Illustrative bounds on a binary interaction",
source = "Constructed example", status = "elicited",
analysis_scale = "standardized_mean_difference"
)
Record scientifically interpretable sensitivity bounds
Description
Record scientifically interpretable sensitivity bounds
Usage
masmr_bounds(
lower,
upper,
meaning,
units,
justification,
source,
status,
analysis_scale,
calibration = NULL
)
Arguments
lower, upper |
Named finite coefficient limits with identical names. |
meaning, units, justification, source |
Nonempty text, scalar or one per term. Record what is bounded, coefficient units, scientific rationale and source. |
status |
One of |
analysis_scale |
Analysis scale, e.g. |
calibration |
Optional record of the calibration inputs and assumptions. |
Value
A bounds object retaining limits, rationale and calibration. No default numeric bounds are chosen. External confidence limits are not hard bounds.
Examples
masmr_bounds(
lower = c("S:M" = -.1), upper = c("S:M" = .1),
meaning = "Assessment-by-group interaction", units = "SMD",
justification = "Illustrative bounds on a binary interaction",
source = "Constructed example", status = "elicited",
analysis_scale = "standardized_mean_difference"
)
Substantive contrasts under common methodological conditions
Description
Compare two complete substantive scenarios using the same methodological profiles and target weights. The estimand is a standardized difference in fitted mean effects, not a prediction interval for a new study.
Usage
masmr_contrast(
object,
substantive,
methodology,
target_weights = NULL,
inference = c("model", "KH", "mKH", "robust"),
level = 0.95,
warn_support = TRUE,
outcome = NULL
)
Arguments
object |
A fitted |
substantive |
A named list of exactly two one-row data frames. The result is the second scenario minus the first. Supply every substantive variable, including substantive covariates held constant. |
methodology |
A nonempty data frame containing all methodology variables. Each row defines one target profile. A single row defines a reference-profile contrast. No ideal profile is chosen automatically. |
target_weights |
Nonnegative finite weights, one per target row, with positive sum. Normalized to sum to one; default equal profile weights. These are target weights, not the fitting precision weights. Repeated rows are retained, so study-level rather than effect-level targets must be built explicitly when studies contribute several effects. |
inference |
One of |
level |
Confidence level in (0,1). |
warn_support |
Warn when positively weighted target rows have absent categorical combinations or lie outside observed continuous ranges. |
outcome |
Outcome name(s) for an outcome-aware fit. NULL returns separate contrasts for every outcome, with cross-outcome covariance. No aggregation. |
Details
The contrast is L beta, with variance L V L'. Nonlinear terms and interactions are rebuilt with the fitted terms and factor coding. Unsupported profiles are never removed or reweighted. Diagnostics describe observed support; they do not establish exchangeability or causal effects. Numeric-coded categories are treated as continuous: use factors for categorical support checks. Range checks are necessary but not sufficient for multivariate overlap; leverage is descriptive, with no calibrated cutoff.
Value
A masmr_contrast list with result, contrast_matrix,
target, support, and covariance of the contrast and two target means.
Formula and outcome-aware workflows are supported. Outcome-specific targets
require explicit outcome and measure metadata.
Target profiles and weights are treated as fixed. Intervals are pointwise.
Examples
dat <- data.frame(study = 1:18, S = rep(c(0, 1, 0), each = 6),
M = rep(c(0, 0, 1), each = 6), vi = .0075)
dat$yi <- .20 + .15 * dat$S - .05 * dat$M + rep(seq(-.02, .02, length.out = 6), 3)
fit <- masmr(dat, "M", "S", formula = yi ~ 1, studyID = "study",
variance = "vi", varcov_type = "univariate", measure = "SMD",
structure = "univariate", tau2 = 0)
target <- list(A = data.frame(S = 0), B = data.frame(S = 1))
masmr_contrast(fit, target, data.frame(M = 0))$result
Specify candidate response-surface departures
Description
Specify candidate response-surface departures
Usage
masmr_departures(formula, by_outcome = FALSE)
Arguments
formula |
One-sided formula for additional functions, e.g. |
by_outcome |
Use separate departure coefficients per multivariate outcome. |
Value
A departure specification for masmr_sensitivity().
Examples
masmr_departures(~ S:M)
Sensitivity of a substantive contrast to bounded methodological departures
Description
Sensitivity of a substantive contrast to bounded methodological departures
Usage
masmr_sensitivity(
object,
substantive,
methodology,
departures,
bounds,
target_weights = NULL,
outcome = NULL,
covariance = c("fitted", "known", "refit"),
total_covariance = NULL,
inference = c("model", "KH", "mKH", "robust"),
level = 0.95,
grid = NULL,
threshold = 0,
rank_tol = 1e-09,
adjustment = c("none", "bonferroni")
)
Arguments
object |
Fitted MASMR object with target-design support. |
substantive, methodology, target_weights, outcome |
Target arguments as in
|
departures |
A |
bounds |
Scientifically described |
covariance |
|
total_covariance |
Known total covariance in analysis_data row order, only for covariance="known". Includes sampling covariance AND heterogeneity. |
inference |
|
level |
Confidence level. |
grid |
Optional explicit departure grid (matrix with named columns). Required for refit; robust/KH fitted-weight intervals also require a grid. Such envelopes cover the declared finite grid only, not a continuous box. |
threshold |
Substantive threshold in analysis-scale effect units, scalar or named per returned outcome. |
rank_tol |
Relative singular-value tolerance for structural diagnostics. |
adjustment |
Multiplicity control: none (pointwise) or bonferroni across returned outcome targets. Known-normal guarantees require fixed targets. |
Details
With A=(X'WX)^{-1}X'W,
D=LAQ-K and bias D\gamma, the fixed-weight
corrected estimate is LAy-D\gamma. Box bounds give exact point ranges.
Normal known-covariance union envelopes have at least nominal pointwise
coverage if the true departure is inside the fixed class and errors are
normal. Fitted and refit intervals are approximate. Bounds are not learned
from the outcome; data-dependent elicitation is outside that guarantee.
This is sensitivity to specified functions of recorded moderators, not
correction for arbitrary unmeasured confounding or a new regression estimator.
Different outcome scales are never averaged or silently back-transformed.
With shared EM-completed predictors, results have
inference_status = "conditional_single_completion", including
known-covariance calculations. Imputation uncertainty is not propagated;
known covariance does not supply an unconditional missing-data guarantee.
Value
A masmr_sensitivity object with result, distortion components, estimability, information, target, bounds and optional grid evaluations.
Examples
dat <- data.frame(study = 1:18, S = rep(c(0, 1, 0), each = 6),
M = rep(c(0, 0, 1), each = 6), vi = .0075)
dat$yi <- .20 + .15 * dat$S - .05 * dat$M + rep(seq(-.02, .02, length.out = 6), 3)
fit <- masmr(dat, "M", "S", formula = yi ~ 1, studyID = "study",
variance = "vi", varcov_type = "univariate", measure = "SMD",
structure = "univariate", tau2 = 0)
target <- list(A = data.frame(S = 0), B = data.frame(S = 1))
bounds <- masmr_bounds(
lower = c("S:M" = -.1), upper = c("S:M" = .1),
meaning = "Assessment-by-group interaction", units = "SMD",
justification = "Illustrative bounds on a binary interaction",
source = "Constructed example", status = "elicited",
analysis_scale = "standardized_mean_difference"
)
masmr_sensitivity(fit, target, data.frame(M = 1),
masmr_departures(~ S:M), bounds)$result
Diagnose support for a MASMR substantive contrast
Description
Diagnose support for a MASMR substantive contrast
Usage
masmr_support(
object,
substantive,
methodology,
target_weights = NULL,
outcome = NULL
)
Arguments
object |
A fitted |
substantive |
A named list of exactly two one-row data frames. The result is the second scenario minus the first. Supply every substantive variable, including substantive covariates held constant. |
methodology |
A nonempty data frame containing all methodology variables. Each row defines one target profile. A single row defines a reference-profile contrast. No ideal profile is chosen automatically. |
target_weights |
Nonnegative finite weights, one per target row, with positive sum. Normalized to sum to one; default equal profile weights. These are target weights, not the fitting precision weights. Repeated rows are retained, so study-level rather than effect-level targets must be built explicitly when studies contribute several effects. |
outcome |
Outcome name(s) for an outcome-aware fit. NULL returns separate contrasts for every outcome, with cross-outcome covariance. No aggregation. |
Value
A list with profile-level flags, weighted flagged share by scenario,
counts and substantive ranges by categorical methodological combination,
and the substantive information matrix after partialling out methodology
at the joint fitted weights. Counts of studies are not robust clusters.
With EM completion, data_basis identifies completed-predictor geometry;
imputed values do not establish observed support.
Examples
dat <- data.frame(study = 1:18, S = rep(c(0, 1, 0), each = 6),
M = rep(c(0, 0, 1), each = 6), vi = .0075)
dat$yi <- .20 + .15 * dat$S - .05 * dat$M + rep(seq(-.02, .02, length.out = 6), 3)
fit <- masmr(dat, "M", "S", formula = yi ~ 1, studyID = "study",
variance = "vi", varcov_type = "univariate", measure = "SMD",
structure = "univariate", tau2 = 0)
target <- list(A = data.frame(S = 0), B = data.frame(S = 1))
masmr_support(fit, target, data.frame(M = 0))
Math Correlations Data
Description
Seven study-level correlation matrices for achievement and mathematics teaching-efficacy variables. The object is stored as a list containing the correlation matrices and their corresponding sample sizes, and is useful for examples involving correlation-matrix synthesis and path modeling.
Usage
math_correlations
Format
A nested list with two elements:
- math_correlations
A named list of seven 3-by-3 correlation matrices. Matrix variables are
ACH(achievement),PTE(personal teaching efficacy), andGTE(general teaching efficacy).- sample_size
Numeric vector of study sample sizes aligned with
math_correlations.
Source
Packaged example data derived from the math-correlation examples in
the source repository; see data-raw/math-corr.r.
Examples
math_correlations
Mixed Correlations of Study-Level Effect Sizes and Moderators
Description
Compute correlations across rows of effect sizes and moderators, with consistently weighted observed-scale correlations by default. This estimates associations among study-level quantities; it does not pool participant-level correlation matrices reported by multiple studies.
Usage
mixed_corr_meta(
data,
outcome = "yi",
variance = "vi",
moderators,
variable_types = NULL,
bootstrap = 1000,
seed = NULL,
use_fisher_z = TRUE,
min_non_missing = 4,
correlation_scale = c("observed", "latent"),
weighting = c("inverse_variance", "none", "outcome_only"),
fallback = c("error", "observed"),
cluster_id = NULL
)
Arguments
data |
A data frame containing the outcome, variance, and moderator columns. |
outcome |
Name of the effect-size column (for example, |
variance |
Name of the sampling-variance column used to define
inverse-variance weights (for example, |
moderators |
Character vector of moderator variable names. |
variable_types |
Optional named character vector with values in
|
bootstrap |
Number of bootstrap resamples for estimating the variance-covariance matrix. |
seed |
Optional random seed for reproducibility. |
use_fisher_z |
Logical; if |
min_non_missing |
Minimum non-missing pairwise observations required to compute a correlation. |
correlation_scale |
|
weighting |
|
fallback |
|
cluster_id |
Optional independent study/cluster column. Bootstrap sampling retains all rows within each sampled cluster. Without this argument, rows are assumed independent and are resampled individually. |
Details
Observed binary values are coded 0/1 in sorted level order; the continuous- binary correlation is point-biserial and the binary-binary correlation is phi. Ordinal variables use their ordered factor levels (or sorted supplied scores). Numeric-score correlations depend on that scoring choice. Unordered factors with more than two levels need an explicit scientifically justified type/order.
The observed weighted estimator divides the weighted centered cross-product
by the product of weighted standard deviations. Pairwise complete rows are
used. Common weights give a common target when observations are complete;
differing missing-data patterns can still produce an indefinite matrix.
effective_n is Kish's weight diagnostic, not inferential degrees of freedom.
Latent estimators assume underlying Gaussian variables and ordered thresholds. Weighted marginal category proportions determine thresholds. Polyserial fitting uses conditional category probabilities after weighted standardization of the continuous variable. Polychoric/tetrachoric fitting maximizes the weighted contingency-table likelihood using numerical bivariate-normal rectangle probabilities. The correlation search is restricted to (-.995,.995); boundary estimates are failures. Latent values describe underlying continuous variables and are not interchangeable with observed binary/ordinal correlations. Explicit fallback can change the estimand and must be inspected in method labels and bootstrap diagnostics. No optional correlation package is required.
Bootstrap draws recompute the selected estimators and weights jointly.
Draws with a missing correlation are rejected; requested, accepted and rejected
counts and the independent-unit count are retained. The estimated covariance
is inspectable in varcov_matrix, but the downstream matched covariance is
withheld unless at least 50 draws and 80 percent of requested draws succeed.
With use_fisher_z=TRUE, covariance of transformed draws is back-transformed
using a diagonal delta-method Jacobian; FALSE uses empirical raw-r covariance.
Stored draws remain on the raw-r scale. A specified seed preserves the caller's
RNG state. Large bootstrap counts reduce Monte Carlo error but do not create
additional independent studies.
min_eigenvalue diagnoses matrix validity; no automatic matrix repair occurs.
The adapter contains sampling covariance, not a between-study Tau estimate.
path_model() can fit WLS with this matched covariance. Such a model describes
associations among the study-level variables, not participant-level causal paths.
Value
A list with class "mars_corr":
- corr_matrix
Estimated study-level correlation matrix.
- varcov_matrix
Bootstrap variance-covariance matrix of pooled correlations in column-major lower-triangle order.
- method_matrix
Matrix recording the method used for each pair.
- pair_details
Data frame with pair, estimate, weighting, and method details.
- mars_object
A compact object directly consumable by path_model.
Examples
out <- mixed_corr_meta(
data = teacher_expectancy,
outcome = "yi",
variance = "vi",
moderators = c("year", "weeks"),
bootstrap = 50,
seed = 123
)
model <- "yi ~ year + weeks"
fit <- path_model(out, model = model, adjust_se = TRUE)
Fit Path Models to a Correlation Matrix
Description
Fit Path Models to a Correlation Matrix
Usage
model_fit(model_input, R, method_null = "sem", N)
Arguments
model_input |
Model input as a character string. Multiple models need
to be on their own line. Regression paths use |
R |
A named correlation matrix, typically the pooled correlation matrix
extracted from a fitted |
method_null |
Null-model method for observed-variable path models.
Currently |
N |
Sample size greater than one, used for single-sample normal-theory
statistics and conditional covariance. These statistics do not account
for meta-analytic synthesis; use |
Details
model_fit() chooses between two fitting paths based on the syntax in
model_input.
Numerical asymmetry below a relative tolerance of 1e-6 is symmetrized;
larger asymmetry and non-positive-definite input matrices are rejected.
For observed-variable path models that use only ~, coefficients are
computed algebraically from the supplied correlation matrix. For each
regression equation, standardized coefficients are
R_{xx}^{-1}R_{xy}. The implied residual covariance matrix is assembled
from the observed exogenous correlations and 1 - R^2 residual
variances, and model fit is evaluated with the normal-theory
discrepancy between the observed and implied correlation matrices. The
SEM-style null model is an independence model with the diagonal of
R retained.
For latent-variable or covariance models using =~ or ~~, the
function builds RAM-style directed-effect (A) and residual covariance
(S) matrices and minimizes the normal-theory SEM discrepancy
F(\theta) = \log|\Sigma(\theta)| +
\mathrm{tr}\{R\Sigma(\theta)^{-1}\} - \log|R| - p,
where \Sigma(\theta) is the model-implied correlation matrix for the
observed variables. Optimization is performed with
optim using method = "BFGS", up to 2000
iterations, and a numerical Hessian is requested for downstream uncertainty
calculations. Variance parameters are optimized on the log scale to keep
them positive. Fixed parameters can be supplied as
value * variable; otherwise the first loading for each unscaled latent
factor is fixed to one for marker-variable identification.
Chi-square statistics use (N - 1) * F. Incremental and residual fit
indices are derived from the fitted and null discrepancies. CFI, TLI, and
SRMR are bounded for display, with raw values returned in
fit_index_raw and clipping indicators returned in
fit_index_flags.
Value
A list containing path coefficients, chi-square fit statistics, CFI, TLI, RMSEA, SRMR, raw fit-index values, and flags indicating whether bounded display values were clipped.
Examples
Br <- matrix(c(1.00000000, -0.09773331, -0.1755029, 0.3186775,
-0.09773331, 1.00000000, 0.5271873, -0.4175596,
-0.17550292, 0.5271872, 1.0000000, -0.4006848,
0.31867753, -0.41755963, -0.4006848, 1.0000000),
nrow = 4, byrow = TRUE)
colnames(Br) <- c("Performance", "Self_confidence", "Cognitive", "Somatic" )
rownames(Br) <- colnames(Br)
## Proposed path model
model <- "## Regression paths
Performance ~ Self_confidence + Cognitive + Somatic
Self_confidence ~ Cognitive + Somatic "
N <- 573
model_fit(model_input = model, R = Br,
method_null = "sem", N)
model_fit(model_input = model, R = Br,
method_null = "sem", N )
Nonoverlap of all pairs for single-case phase contrasts
Description
Computes nonoverlap of all pairs (NAP) and a tie-corrected U-statistic variance under independent observations.
Usage
nap_computation(
data,
studyID,
subjectID,
outcome_name,
phase_name,
phase_order = NULL,
improvement = c("increase", "decrease"),
variance_correction = c("none", "autocorrelation"),
na_option = "listwise"
)
Arguments
data |
Data frame containing repeated observations. |
studyID, subjectID, outcome_name, phase_name |
Character strings naming the study, case, outcome, and phase columns. |
phase_order |
Character vector giving the baseline and intervention
labels, in that order. If |
improvement |
Whether an increase or decrease in the outcome is beneficial. |
variance_correction |
Either |
na_option |
Currently only |
Details
NAP is the proportion of baseline-intervention pairs for which the intervention observation is better, counting ties as one-half. The reported variance is the tie-corrected null variance of the corresponding Mann-Whitney U statistic, divided by the squared number of pairs. It is an approximation and should be interpreted cautiously for serially dependent observations.
Value
A data frame with NAP in yi and an approximate variance in vi.
Examples
dat <- data.frame(study = "S1", case = "A", phase = rep(c("A", "B"), each = 3),
outcome = c(1, 2, 2, 3, 4, 5))
nap_computation(dat, "study", "case", "outcome", "phase")
Primary network meta-analysis alternative-estimation function
Description
Primary network meta-analysis alternative-estimation function
Usage
network_alt_estimation(type = c("bootstrap", "jackknife"), ...)
Arguments
type |
Network resampling method: |
... |
Additional arguments passed to the selected network resampling replicate function. |
Value
A list of fitted "nma_mars" replicate objects.
Examples
nma_dat <- data.frame(
study = c("S1", "S2", "S3", "S4"),
treatment_1 = c("A", "A", "B", "A"),
treatment_2 = c("B", "C", "C", "B"),
effect = c(0.20, 0.35, 0.10, 0.15),
variance = c(0.04, 0.05, 0.04, 0.06)
)
nma_reps <- network_alt_estimation(
type = "bootstrap",
number_bootstraps = 2,
data = nma_dat,
study_id = "study",
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
effect = "effect",
variance = "variance",
model_type = "wls"
)
Construct network contrasts and covariance from independent arms
Description
One measurement per study and treatment is supported. For repeated continuous
outcomes or times use network_meta_repeated() or network_smd_data(). MD uses
independent arm mean variances; binary effects use normal/delta approximations.
SMD delegates to the joint delta-method constructor.
Usage
network_arm_data(
data,
study_id,
treatment,
measure = c("MD", "SMD", "logOR", "logRR", "RD"),
mean = NULL,
sd = NULL,
n = "n",
events = NULL,
correction = 0.5
)
Arguments
data |
Arm-level data. |
study_id, treatment |
Column names identifying studies and treatments. |
measure |
|
mean, sd, n |
Column names for continuous summaries and sample sizes. |
events |
Event-count column for binary measures. |
correction |
Nonnegative continuity correction for logOR/logRR. Applied to events and nonevents in every arm of a study with a zero cell. Zero correction rejects such studies rather than producing infinite effects. |
Value
A list containing contrast data, named study sampling_covariance
blocks, and metadata. Effects are treatment_2 minus treatment_1 on the chosen
scale. The first sorted arm within each study is the contrast baseline;
the analysis reference is independently selected when fitting.
Examples
arms <- data.frame(study = 1, treatment = c("A", "B", "C"),
m = c(10, 12, 13), s = c(3, 4, 3), n = c(25, 30, 28))
network_arm_data(arms, "study", "treatment", "MD", mean = "m", sd = "s")
Small-study asymmetry test for network meta-analysis
Description
Fits effects jointly on sampling SE and the network mean design (or direct comparison/outcome/time strata). Uses fitted total covariance for GLS and study-cluster CR1 covariance with G-1 t inference. The comparison-based intercept row is the sampling-SE coefficient, equivalent to an asymmetry intercept on the standardized scale. Comparison centers are estimated jointly, not treated as known offsets. Parent covariance is held fixed. More studies than fitted regression parameters are required. Cross-study covariance is unsupported. A shared asymmetry slope requires prespecified meaningful contrast directions. Effect-SE coupling can produce artefactual asymmetry for some effect measures. Fewer than ten independent studies and little SE variation are flagged in diagnostics; ten is a rule of thumb, not a reliability guarantee. Asymmetry does not establish publication bias, and nonsignificance does not exclude it.
Usage
network_bias_test(
object,
center = c("network", "direct"),
comparison_adjusted = TRUE
)
Arguments
object |
A fitted |
center |
Centering method for comparison adjustment; |
comparison_adjusted |
Logical; if |
Value
A list with GLS coefficients, study-cluster CR1 covariance, G-1 degrees of freedom, sampling-SE asymmetry coefficient in intercept, fitted design/data, conditional_covariance=TRUE and interpretation diagnostics.
Examples
network_bias_test(nma_fit)
Estimate arbitrary complex interventions from a component NMA
Description
Estimate arbitrary complex interventions from a component NMA
Usage
network_complex_effect(
object,
intervention,
comparator = NULL,
level = object$level,
backtransf = FALSE
)
Arguments
object |
A |
intervention |
Character vector of complex interventions, or a single integer giving the size of all component combinations to generate. |
comparator |
Optional comparator intervention. If |
level |
Confidence level. |
backtransf |
Logical; if |
Value
A data frame with estimated effects for arbitrary complex interventions or intervention comparisons.
Examples
cnma_fit <- network_component_meta(nma_fit)
network_complex_effect(cnma_fit, intervention = "B", comparator = "A")
Additive component network meta-analysis
Description
Additive component network meta-analysis
Usage
network_component_meta(
object,
inactive = NULL,
sep_components = "+",
C_matrix = NULL,
level = 0.95
)
Arguments
object |
A fitted |
inactive |
Optional component with no active effect. Rows containing the inactive component are retained, but the inactive component column is removed from the additive model. |
sep_components |
Separator used to split treatment names into
components. Defaults to |
C_matrix |
Optional treatment-by-component matrix. Row names must match
|
level |
Confidence level for component and fitted-combination intervals. |
Value
A cnma_mars object with component effects, fitted treatment
combinations, the C matrix, and additive model diagnostics.
Examples
cnma_fit <- network_component_meta(nma_fit)
cnma_fit$component_effects
Heatmap for Network Contribution Matrix
Description
Draws a base R heatmap from the contribution_matrix stored in a fitted
network_meta object.
Usage
network_contribution_heatmap(
nma_object,
main = NULL,
xlab = NULL,
ylab = "Network Comparison",
low = "#F7FBFF",
mid = "#6BAED6",
high = "#08306B",
n_colors = 100,
show_values = FALSE,
value_digits = 1,
value_cex = 0.6,
text_col = "#111111",
show_legend = TRUE,
legend_side = c("right", "left"),
legend_title = NULL,
main_adj = 0.5,
main_line = NULL,
strata = NULL,
limits = c(0, 100),
comparisons = c("all", "reference")
)
Arguments
nma_object |
A fitted object returned by |
main |
Plot title. |
xlab |
Label for the x-axis. |
ylab |
Label for the y-axis. |
low |
Color for low contributions. |
mid |
Color for mid contributions. |
high |
Color for high contributions. |
n_colors |
Number of colors in the gradient. |
show_values |
Logical; if |
value_digits |
Digits for printed percentages. |
value_cex |
Text size for printed percentages. |
text_col |
Color for printed values. |
show_legend |
Logical; if |
legend_side |
Side for the color legend: |
legend_title |
Title for the heatmap color legend. |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
strata |
Named list selecting fitted outcome/time values. |
limits |
Fixed color scale, default 0 to 100 percent. |
comparisons |
|
Value
Invisibly returns the contribution matrix used in the plot.
Examples
network_contribution_heatmap(nma_fit)
Sensitivity to specified sampling covariance assumptions
Description
Refit a joint network model under analyst-specified within-study sampling covariances while retaining the same effects, mean model and random-effect structure.
Usage
network_covariance_sensitivity(object, covariance_scenarios)
Arguments
object |
A fitted joint network model. |
covariance_scenarios |
Uniquely named list of full sampling covariance matrices or named study-block lists. Dimensions must be named by observation ID. |
Details
Each scenario replaces sampling covariance S, not the heterogeneity covariance.
The function performs a complete refit, retaining reference, strata, moderators,
random grouping levels, estimation method and inference choice. Heterogeneity is
re-estimated unless fixed in the original model.
Covariance names are aligned to the fitted observation IDs. Every scenario must retain the original marginal sampling variances, be symmetric and valid under the model's positive-definiteness checks, and have zero cross-study covariance. Each study-block list must contain exactly the fitted studies. Invalid scenarios raise an error; no correlation or participant-overlap information is imputed.
Compare treatment estimates, standard errors, intervals, heterogeneity and convergence across plausible scenarios. Stability supports robustness to those specific dependence assumptions, not to all possible assumptions. An independence scenario for shared-arm data is a deliberate sensitivity perturbation, not evidence that those sampling errors are independent. The function does not select a best scenario or perform a statistical test of covariance correctness. Changing the effects, standardizer or marginal variances requires a separately specified analysis.
Value
A named list of refitted joint network objects, one per scenario. The model interface and prediction metadata are retained. No automatic difference difference table or hypothesis test is computed. Treatment p-value adjustment is retained and recalculated for each refit.
See Also
network_influence(), network_meta(), network_smd_data().
Examples
d <- data.frame(id=paste0("i",1:12),study=rep(1:6,each=2),a="A",
b=rep(c("B","C"),6),effect=rep(c(.3,.6),6),variance=.04)
S0 <- diag(d$variance);dimnames(S0)<-list(d$id,d$id)
S1 <- S0
for(ii in split(seq_len(nrow(d)),d$study)) S1[ii,ii]<-matrix(c(.04,.015,.015,.04),2)
fit <- network_meta(d,"study","a","b","effect","variance",
observation_id="id",sampling_covariance=S1)
sensitivity <- network_covariance_sensitivity(fit,list(independent=S0,shared=S1))
vapply(sensitivity,function(x) x$effects$total_se[1],numeric(1))
Between-design disagreement after detaching individual designs
Description
Intended question: how much between-design disagreement remains when each treatment design, in turn, is allowed its own treatment effects?
Usage
network_design_detachment(object)
## S3 method for class 'nma_design_detachment'
print(
x,
...,
digits = getOption("digits"),
estimable_only = TRUE,
detailed = FALSE
)
## S3 method for class 'nma_design_detachment'
summary(
object,
...,
digits = getOption("digits"),
estimable_only = TRUE,
detailed = FALSE
)
Arguments
object |
A fitted joint coherent network model; for |
x |
A result from |
... |
Additional arguments forwarded to |
digits |
Decimal places, an integer from 1 to 22; defaults to
|
estimable_only |
Logical; show only detachable designs with positive
remaining df (default |
detailed |
Logical; show all diagnostic columns and assumptions
(default |
Details
A design is the set of treatments observed in a study. For each design, add interactions between its indicator and the basic treatment-effect columns, retaining only columns that increase the mean-model rank. Studies and sampling covariance are retained; detachment is not deletion or leave-one-design-out refitting. Existing moderator slopes remain shared and mean strata retain their fitted structure.
Let X be the coherent mean matrix, A the full design-by-treatment mean matrix,
and B the coherent mean augmented for the selected design. Using sampling
covariance S alone, define Q(M) as the GLS residual quadratic form for M.
The baseline between-design statistic is Q(X)-Q(A). After detachment it is
Q(B)-Q(A), with df equal to rank(A)-rank(B). The reference is chi-squared.
No random-effects covariance is used or re-estimated, even for random-effects
input. This corresponds to the sampling-only Q.inc.detach assessment in
netmeta::decomp.design() for equivalent inputs and mean models, rather than
its random-effects global Higgins test.
The printout follows the question with the null hypothesis that no between- design disagreement remains after the selected design is allowed separate effects. The baseline test separately states its null of no between-design disagreement in the original network.
Each p-value tests the remaining between-design disagreement, not whether the
detached design is individually inconsistent. These overlapping exploratory
results are unadjusted. A change in p-value also reflects changing df; it does
not establish that a design is erroneous or justify excluding its studies.
Designs adding no independent parameters, or whose full design effects cannot
be separated from the remaining network, have detachable=FALSE. They are
retained for inspection but have no detachment p-value.
Zero remaining df has no p-value. Default printing shows only detachable designs
with a testable remaining statistic, ordered by increasing Q.
Value
A list of class nma_design_detachment with global (baseline Q, df,
p-value), detached (design, remaining Q, df, p-value, added_df, design_df, detachable,
estimable, and reason), question, and assumption. All designs are
retained in the returned data. Print/summary support decimal places,
estimable-only selection and detailed diagnostic fields.
References
Krahn, U., Binder, H. and Koenig, J. (2013). A graphical tool for locating inconsistency in network meta-analyses. BMC Medical Research Methodology, 13, 35. doi:10.1186/1471-2288-13-35.
See Also
network_heterogeneity(), network_q_decomposition(),
network_design_incoherence(), network_influence()
Examples
d <- data.frame(s=1:9,a=rep(c("A","A","B"),3),b=rep(c("B","C","C"),3),
g=rep(c(.2,.6,.2),3),v=.04)
fit <- network_meta_coherent(d,"s","a","b","g","v",diagnostics=FALSE)
network_design_detachment(fit)
Higgins design-by-treatment incoherence tests
Description
Intended question: is there disagreement across treatment designs anywhere in the network? Assess whether treatment means can be described by a coherent network after accounting for the specified sampling covariance and treatment heterogeneity. Available for all three joint network interfaces.
Usage
network_design_incoherence(
object,
method = c("wald", "conditional", "ML"),
adjust = c("none", "holm", "bonferroni"),
local_covariance = c("gls", "observed")
)
## S3 method for class 'nma_design_incoherence'
print(
x,
...,
digits = getOption("digits"),
estimable_only = TRUE,
detailed = FALSE
)
## S3 method for class 'nma_design_incoherence'
summary(
object,
...,
digits = getOption("digits"),
estimable_only = TRUE,
detailed = FALSE
)
Arguments
object |
A fitted joint network model from |
method |
|
adjust |
Multiplicity correction for the local design-deviation tests:
|
local_covariance |
Covariance for local symmetric side-splitting Wald
tests: |
x |
A result from |
... |
Additional print arguments forwarded to |
digits |
Decimal places to display, an integer from 1 to 22.
Defaults to |
estimable_only |
Logical; show only estimable tests (default |
detailed |
Logical; show all diagnostic columns (default |
Details
Printed output states the research question and global null hypothesis that all identifiable design-by-treatment interaction parameters are zero. The local section separately states that each pair's identifiable targeted deviation parameters are zero under the symmetric side-splitting model (White, 2015).
The null mean model is E(y_i)=X_i d. The alternative adds columns
W_i\gamma; the null hypothesis is that all identifiable added
coefficients are zero. Covariance remains sampling covariance plus the selected
signed random-treatment covariance. Only columns increasing the mean-design rank
are retained. Thus df is the number of independently testable added parameters,
not the number of graphical triangles.
Global test. A study design is the set of treatments observed in that
study, across its rows. The function interacts design indicators with the basic
treatment-effect design Z. Mean strata receive separate interactions when
specified. Existing moderator slopes remain in the mean model; this extension
does not add design-specific moderator slopes. The joint test assesses
between-design disagreement. Within-study multi-arm contrast identities are
preserved, so a triangle supplied solely by one common multi-arm design does not
create an independent incoherence parameter.
Local tests. For each unordered treatment pair A/B, eligible designs contain both treatments. Treatment B is perturbed by +1/2 and A by -1/2 in those studies; other treatments are unchanged. The perturbation of a contrast is the second treatment's shift minus the first's. One added column is constructed per mean stratum. These are White's (2015, section 3.6, Table 1) symmetric side-splitting tests, preserving multi-arm identities. They are not independent direct/indirect splits, and a significant result does not uniquely identify a problematic comparison or study. Qin et al. (2024, equation 3) describe the symmetric side-splitting model and its restrictions relative to the full design-by-treatment interaction model.
The local mean model is E(y)=Xd+w_{AB}\gamma_{AB}. The sign of gamma
follows treatment B minus A, shown in contrast. For a single estimable
coefficient, local reports gamma, se_gamma, ci_lower, and ci_upper.
The intervals are pointwise 95% normal Wald intervals, regardless of adjust
or the primary fit's confidence level. With augmented matrix A and fitted total
covariance V, GLS coefficient covariance is (A^T V^{-1} A)^{-1}. Its added
coefficient block supplies gamma's covariance with local_covariance="gls";
heterogeneity estimation uncertainty is then not additionally propagated.
For multiple mean strata,
local_coefficients reports each retained gamma separately while local
retains the joint test. Scalar gamma fields are missing when more than one
coefficient is tested. A likelihood-ratio test still reports Wald coefficient
intervals, which need not agree with its p-value.
Refitted Wald calculation. Fit the augmented design-by-treatment mean
model by REML and jointly test its identifiable added coefficients using their
model covariance and a chi-squared reference. Heterogeneity is estimated under
this alternative, unless fixed through tau2 or heterogeneity="none".
This follows Higgins et al. and White et al. (2012). Failure to identify or
estimate the alternative is reported as nonestimable, rather than as agreement.
Observed-information local covariance. With method="wald" and
local_covariance="observed", let theta contain the free heterogeneity
covariance parameters, V=V(theta), and A the augmented local mean matrix.
The joint observed information is the Hessian, with respect to both beta and
theta, of
\tfrac12[\log|V|+(y-A\beta)^T V^{-1}(y-A\beta)+\log|A^T V^{-1}A|].
It is evaluated at the REML heterogeneity estimate and its GLS beta estimate.
The beta block of its inverse supplies the local coefficient covariance,
retaining the cross-information between mean and heterogeneity parameters.
This is not the Hessian of the profiled REML criterion with respect to beta.
gls instead inverts only the mean-information block. The observed option is
model-based and asymptotic, not a small-sample correction or a sandwich variance.
Pointwise 95% intervals still use normal quantiles and Holm still adjusts only
local p-values. White's Stata mvmeta default includes heterogeneity uncertainty;
its nouncertainv option describes the alternative conditional calculation.
The observed calculation supports the fitted linear variance-component kernels
and interior unstructured heterogeneity covariance. Fixed tau2 and
heterogeneity="none" have no estimated variance parameters, so both covariance
options reduce to GLS. An estimated variance on a boundary, singular information,
or non-positive-definite joint information makes the local test unavailable:
estimable=FALSE and reason explains why. No automatic GLS fallback or
positive-definiteness repair is performed. Use detailed=TRUE and
estimable_only=FALSE to inspect such rows. The default global GLS Wald test
is unaffected; conditional and ML tests reject the observed option explicitly.
Conditional calculation. Refit the augmented mean by generalized least
squares using the original fitted total covariance. Compute
Q=\hat\gamma^T\operatorname{Var}(\hat\gamma)^{-1}\hat\gamma and use a
chi-squared reference distribution with df degrees of freedom. This conditions
on fitted heterogeneity and does not propagate its estimation uncertainty.
ML calculation. Refit both null and alternative using ML, even when
the primary fit used REML. Calculate D=2(\ell_{alternative}-\ell_{null})
and compare with chi-squared(df). Heterogeneity is re-estimated unless the
original model fixed it through tau2 or heterogeneity="none". REML likelihoods
are not compared across different mean designs. Alternative optimization or
identifiability failures are marked in the output.
Interpretation. A small p-value indicates evidence against the specified
coherent mean model, conditional on its covariance and effect-modifier
assumptions. It does not measure the size or clinical importance of disagreement.
Use network_nodesplit() to examine direct-minus-indirect effects and intervals,
and network_influence() to investigate sensitivity. Large p-values can reflect
low power; they do not establish coherence or transitivity. Global and local
reference distributions are asymptotic. Local p-values are not multiplicity
adjusted unless adjust is supplied, and tests use model-based covariance even
for a primary CR1 fit. Local tests overlap: their statistics and df cannot be
summed to obtain within-design heterogeneity. Use network_q_decomposition().
Value
A list of class nma_design_incoherence containing:
- global
One-row table with
statistic,df,p_value, andestimable.- local
The same fields for each treatment pair, plus
comparison. A local row can jointly test several mean-stratum parameters.p_adjustedcontains multiplicity-adjusted p-values. For one estimable coefficient,gamma,se_gamma,ci_lower, andci_uppergive the signed departure, its model-based SE and pointwise 95% interval;contraststates direction.- local_coefficients
One row per pair and mean stratum, including
gamma,se_gamma,ci_lower,ci_upper, andestimable. Unavailable coefficients have missing estimates.- local_covariance
Requested local coefficient covariance:
glsorobserved. Fixed heterogeneity makes the two calculations identical.- adjustment
Local multiplicity method, family description and size.
- method, assumption
Descriptions of the calculation and interpretation.
With method="wald" or method="ML", test tables also contain null_heterogeneity,
alternative_heterogeneity, convergence codes (zero indicates convergence), and
reason. Scalar variance components are labelled; unstructured matrices are
flattened in column-major basic-effect coordinate order. These strings are
summaries, not confidence intervals. Nonestimable tests have estimable=FALSE
and missing statistics/p-values; this is different from failing to reject a null.
Printing shows the global test and estimable local tests, with shared settings
reported once. Constant local df is printed above the results. With no local
adjustment, the duplicate adjusted-p column is omitted. Alternative-model
heterogeneity, convergence codes and nonestimability reasons remain in the
returned tables. Use print(result, detailed=TRUE, estimable_only=FALSE) to
inspect all diagnostic fields and rows. Display filtering does not change the
multiplicity family. summary(result, digits=3) remembers display preferences;
explicit print arguments override them. No stored values are rounded.
References
Higgins, J. P. T., Jackson, D., Barrett, J. K., Lu, G., Ades, A. E., and White, I. R. (2012). Consistency and inconsistency in network meta-analysis: concepts and models for multi-arm studies. Research Synthesis Methods, 3, 98–110. doi:10.1002/jrsm.1044.
White, I. R., Barrett, J. K., Jackson, D., and Higgins, J. P. T. (2012). Consistency and inconsistency in network meta-analysis: model estimation using multivariate meta-regression. Research Synthesis Methods, 3, 111–125. doi:10.1002/jrsm.1045.
White, I. R. (2015). Network meta-analysis. The Stata Journal, 15(4), 951–985. Section 3.6, Table 1. doi:10.1177/1536867X1501500403.
Qin, L., Zhao, S., Guo, W., Tong, T., and Yang, K. (2024). A comparison of two models for detecting inconsistency in network meta-analysis. Research Synthesis Methods, 15(6), 851–871. doi:10.1002/jrsm.1734.
See Also
network_incoherence(), network_nodesplit(),
network_transitivity(), network_incoherence_plot().
Examples
d <- data.frame(study=1:9, a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3), effect=rep(c(.2,.6,.2),3), variance=.04)
fit <- network_meta(d,"study","a","b","effect","variance")
network_design_incoherence(fit)$global
network_design_incoherence(fit,method="ML")$local
network_design_incoherence(fit,local_covariance="observed")$local
Overlay Forest Plot for Direct, Indirect, and Total Network Effects
Description
Draws a comparison-level forest plot with nearly overlapping lines for direct,
indirect, and total effects from a fitted network_meta object.
Usage
network_forest_overlay_plot(
nma_object,
ci_level = 0.95,
order_by = c("total", "abs_total", "comparison"),
decreasing = FALSE,
xlab = NULL,
main = "Direct, Indirect, and Total Effects",
ref_line = 0,
line_offsets = c(direct = -0.14, total = 0, indirect = 0.14),
colors = c(direct = "#2C7FB8", total = "#111111", indirect = "#D95F0E"),
pch = c(direct = 15, total = 19, indirect = 17),
line_types = c(direct = 2, total = 1, indirect = 3),
line_lwd = 2,
point_cex = 0.8,
label_cex = 0.8,
right_label = c("all", "total", "none"),
right_digits = 3,
ref_col = "gray55",
legend_position = "bottom",
legend_title = NULL,
main_adj = 0.5,
main_line = NULL,
strata = NULL,
facet = TRUE,
prediction = FALSE,
benefit_direction = NULL,
label_width = 32
)
Arguments
nma_object |
A fitted object returned by |
ci_level |
Confidence level for interval bounds. Defaults to |
order_by |
Ordering rule for rows. One of |
decreasing |
Logical; whether to reverse the selected order. |
xlab |
Label for x-axis. |
main |
Plot title. |
ref_line |
Vertical reference line location. Defaults to |
line_offsets |
Named numeric vector for vertical offsets of
|
colors |
Named color vector for |
pch |
Named point-symbol vector for |
line_types |
Named line-type vector for |
line_lwd |
Confidence interval line width. |
point_cex |
Point size scaling. |
label_cex |
Label size scaling. |
right_label |
One of |
right_digits |
Number of digits shown in right-side labels. |
ref_col |
Color of the vertical reference line. |
legend_position |
Legend position. Use |
legend_title |
Optional legend title. |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
strata |
Named list selecting fitted outcome/time values. |
facet |
Draw separate panels for outcome/time strata. |
prediction |
Add dashed prediction intervals for total effects. |
benefit_direction |
Optional |
label_width |
Approximate character width for wrapping comparison labels. |
Details
Intervals are recalculated at the requested confidence level using the fitted contrast degrees of freedom. Missing evidence is labelled explicitly. Facets share a horizontal scale. Increase export height for multiple panels.
Value
Invisibly returns the plotted data frame.
Examples
network_forest_overlay_plot(nma_fit)
Forest Plot for Network Meta-analysis Effects
Description
Draws a forest plot for one effect type from a fitted
network_meta object.
Usage
network_forest_plot(
nma_object,
effect_type = c("total", "direct", "indirect"),
ci_level = 0.95,
order_by = c("effect", "abs_effect", "comparison"),
decreasing = FALSE,
xlab = NULL,
main = NULL,
ref_line = 0,
point_col = "#0B1F3A",
ci_col = "#2E5A88",
ci_lty = 1,
ci_lwd = 2,
point_pch = 19,
point_cex = 1,
label_cex = 0.8,
right_digits = 3,
right_header = NULL,
ref_col = "gray55",
main_adj = 0.5,
main_line = NULL,
strata = NULL,
facet = TRUE,
prediction = FALSE,
benefit_direction = NULL,
label_width = 32,
comparisons = c("all", "reference")
)
Arguments
nma_object |
A fitted object returned by |
effect_type |
One of |
ci_level |
Confidence level for interval bounds. Defaults to |
order_by |
Ordering rule for rows. One of |
decreasing |
Logical; whether to reverse the selected order. |
xlab |
Label for x-axis. |
main |
Optional title. If |
ref_line |
Vertical reference line location. Defaults to |
point_col |
Point color. |
ci_col |
Confidence interval line color. |
ci_lty |
Confidence interval line type. |
ci_lwd |
Confidence interval line width. |
point_pch |
Point symbol. |
point_cex |
Point size scaling. |
label_cex |
Label size scaling. |
right_digits |
Number of digits shown in right-side labels. |
right_header |
Optional header shown above the right-side CI label column.
If |
ref_col |
Color of the vertical reference line. |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
strata |
Named list selecting fitted outcome/time values. |
facet |
Draw separate panels for outcome/time strata; otherwise include strata in labels. |
prediction |
Add dashed prediction intervals for total effects. |
benefit_direction |
Optional |
label_width |
Approximate character width for wrapping comparison labels. |
comparisons |
|
Details
Intervals are recalculated at the requested confidence level using the fitted contrast degrees of freedom. Missing evidence is labelled explicitly. Facets share a horizontal scale. Increase export height for multiple panels.
Value
Invisibly returns the plotted data frame.
Examples
network_forest_plot(nma_fit, effect_type = "total")
Comparison-adjusted funnel plot for network meta-analysis
Description
Comparison-adjusted funnel plot for network meta-analysis
Usage
network_funnel_plot(
object,
center = c("network", "direct"),
comparison_adjusted = TRUE,
level = 0.95,
xlab = NULL,
ylab = "Standard error",
main = "Comparison-adjusted funnel plot",
pch = 19,
col = "gray30",
trim_fill = FALSE,
...
)
Arguments
object |
A fitted |
center |
Center each direct comparison around |
comparison_adjusted |
Logical; if |
level |
Sampling-guide level in (0,1). Guides are plus/minus the normal quantile times sampling SE; they omit heterogeneity and center uncertainty. |
xlab, ylab, main |
Plot labels. |
pch, col |
Point symbol and color. |
trim_fill |
Must be FALSE. Ordinary trim-and-fill is unsupported for
dependent network contrasts; use comparison-adjusted funnels and |
... |
Additional arguments passed to |
Details
Guides are descriptive sampling-SE lines, not simultaneous intervals or a test for missing evidence. Network centers use row-specific fitted predictions; direct centers use comparison/outcome/time strata and moderators. Prespecify meaningful contrast directions and assess effect-measure suitability.
Value
Invisibly returns effects, sampling SEs, chosen centers and adjusted effects.
Examples
network_funnel_plot(nma_fit)
Base R Network Graph for Network Meta-analysis
Description
Draws a treatment network graph from the direct comparisons in a fitted
network_meta object. Node size and edge width can be scaled by
available direct evidence, similar to common network meta-analysis graph
displays, without requiring graph plotting dependencies.
Usage
network_graph_plot(
nma_object,
main = "Treatment Network",
node_size = c("studies", "effects", "equal"),
edge_width = c("studies", "effects", "equal"),
layout = c("circle"),
node_cex_range = c(2, 7),
edge_lwd_range = c(1, 8),
node_col = "#9ECAE1",
node_border = "#08519C",
edge_col = "#4D4D4D",
label_col = "#111111",
label_cex = 0.9,
edge_label = FALSE,
edge_label_cex = 0.75,
edge_label_col = "#333333",
xlim = NULL,
ylim = NULL,
...,
strata = NULL,
show_multiarm = FALSE,
label_position = c("outside", "above", "below", "left", "right", "center"),
label_offset = 0.06,
edge_label_offset = 0.04,
edge_label_bg = "white"
)
Arguments
nma_object |
A fitted object returned by |
main |
Plot title. |
node_size |
Counts unique studies containing a treatment for |
edge_width |
For |
layout |
Currently |
node_cex_range |
Numeric length-2 range for scaled node sizes. |
edge_lwd_range |
Numeric length-2 range for scaled edge widths. |
node_col |
Node fill color. |
node_border |
Node border color. |
edge_col |
Edge color. |
label_col |
Treatment label color. |
label_cex |
Treatment label size. |
edge_label |
Logical; if |
edge_label_cex |
Edge label size. |
edge_label_col |
Edge label color. |
xlim, ylim |
Optional plot limits. |
... |
Additional arguments passed to |
strata |
Named list selecting fitted outcome/time values. |
show_multiarm |
Shade distinct multi-arm study designs. |
label_position |
Treatment label placement: |
label_offset |
Additional gap beyond the node, in plot-coordinate units
(the circular layout has radius one). Ignored for |
edge_label_offset |
Signed perpendicular gap between study counts and their edges, in plot-coordinate units. Use zero to keep counts on edges. |
edge_label_bg |
Background color behind study counts, drawn after all
edges to keep lines from crossing text. Use |
Value
Invisibly returns a list with nodes and edges data
frames used for plotting.
node_labels and edge_labels give the displayed label coordinates.
Label placement changes only the display, not evidence counts or estimates.
Examples
network_graph_plot(nma_fit)
Profile likelihood interval for common network heterogeneity
Description
Quantify uncertainty in one estimated common between-study treatment-contrast variance using a profiled ML likelihood.
Usage
network_heterogeneity_profile(object, level = 0.95)
Arguments
object |
A joint fit with one estimated common study variance, no
additional random grouping levels, and no fixed |
level |
Coverage for the approximate profile-likelihood interval. |
Details
For each candidate nonnegative \tau^2, build its total study covariance
and maximize the Gaussian ML likelihood over the treatment means by GLS. Find
the ML variance estimate and retain values satisfying
2\{\ell(\hat\tau^2)-\ell(\tau^2)\}\leq\chi^2_{1,level}.
The calculation includes the exact zero boundary. It uses ML even if the fitted
object was estimated by REML, so its returned estimate may differ from the
original object's REML estimate.
tau2 is variance on the squared effect scale; its square root is the between-
study SD. A broad interval indicates weak precision in heterogeneity estimation.
A lower bound of zero means the approximate interval includes zero, not that
homogeneity has been established. The usual one-degree-of-freedom chi-squared
cutoff is approximate and can be inaccurate near a variance boundary or with few
studies. Sampling covariance is treated as known. This is not an incoherence
or transitivity test, and does not profile an unstructured matrix or several
hierarchical variance components. Failure to bracket an upper bound raises an error.
Value
A one-row data frame with the ML tau2 estimate, lower/upper bounds,
requested level, and method. Bounds refer to variance, not its SD.
See Also
network_incoherence(), network_prediction_intervals().
Examples
d <- data.frame(study=1:9,a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3),effect=c(.1,.5,.2,.4,.8,.1,.2,.4,.4),variance=.04)
fit <- network_meta(d,"study","a","b","effect","variance",heterogeneity="common")
network_heterogeneity_profile(fit)
Direct versus indirect network incoherence
Description
Intended question: do direct and independent indirect estimates disagree for
a treatment comparison? This interface uses network_nodesplit().
Usage
network_incoherence(
object,
method = c("conditional", "ML", "wald"),
adjust = c("none", "holm", "bonferroni"),
comparisons = NULL,
level = 0.95
)
## S3 method for class 'nma_incoherence'
print(
x,
...,
estimable_only = TRUE,
row.names = FALSE,
digits = getOption("digits"),
detailed = FALSE
)
## S3 method for class 'nma_incoherence'
summary(
object,
...,
digits = getOption("digits"),
estimable_only = TRUE,
detailed = FALSE
)
Arguments
object |
A fitted joint network model. For the summary method, the data
frame returned by |
method |
|
adjust |
|
comparisons |
Optional data frame with |
level |
Coverage of pointwise normal-approximation intervals for direct effects, indirect effects and their difference. |
x |
The data frame returned by |
... |
Additional print arguments forwarded to |
estimable_only |
Logical; print only estimable rows (default |
row.names |
Logical; print row names. Defaults to |
digits |
Number of decimal places to display, an integer from 1 to
22; defaults to |
detailed |
Logical; show standard errors, intervals and all diagnostic
fields rather than the compact default ( |
Details
Whole studies supplying the target direct contrast are excluded from indirect
evidence, including their other multi-arm contrasts. A multi-arm study cannot
supply its own independent indirect evidence. The contrast direction is
treatment_2 minus treatment_1; difference is direct minus indirect.
The printout states the intended question: do direct and independent indirect
estimates disagree for a treatment contrast? It then states the null hypothesis
for each contrast: direct and independent indirect effects are equal
(difference=0). The z test and p-value test this null, not the network effect
or the direct evidence proportion.
Printed comparisons use an explicit contrast label, for example
Metformin - Acarbose, matching the direction of direct and indirect effects.
Stored treatment_1 and treatment_2 columns are unchanged.
Nonestimable splits retain a reason and missing difference inference.
Printed output shows only estimable comparisons by default. The compact display
includes direct-study count (k), direct evidence proportion (prop), coherent
network estimate, direct/indirect estimates, difference, signed z, and raw and
adjusted p-values. Use detailed=TRUE for SEs, intervals and diagnostic fields.
prop is the ratio of primary model-based network variance to direct-only
variance, rather than a study or patient fraction. It does not use the variance
from the whole-study-exclusion indirect fit.
The returned data frame retains all requested rows, including nonestimable comparisons and
their reasons. Use print(result, estimable_only=FALSE) to display every row.
A shared method is printed once above the results. The estimable column is
omitted when every displayed row is estimable; empty reason columns are
omitted. Mixed methods and nonestimability information remain visible.
summary(result, digits=3) records display precision and returns the complete
result; it does not compute column-wise descriptive statistics. Both summary
and print accept estimable_only, and explicit print arguments override the
choices recorded by summary.
Display filtering does not recalculate multiplicity-adjusted p-values or
change the hypothesis family. If no split is estimable, printing reports that
no estimable direct/indirect comparisons are available.
This is a pair-specific assessment, not an omnibus test. Split tests overlap;
neither their statistics nor their degrees of freedom form an additive
heterogeneity decomposition. Use network_design_incoherence() for Higgins'
design-by-treatment global test and network_heterogeneity() for within-design
variation. Use network_q_decomposition() for total/within/between residual Q.
Migration: earlier development versions returned a global/local design-test
list. Move those calls, including method="conditional" and method="ML", to
network_design_incoherence(). Accessing $global or $local on the new split
table raises a migration error rather than silently returning NULL.
Value
A data frame of class nma_incoherence, with the same columns and
attributes as network_nodesplit(): direct and indirect estimates, SEs and
intervals; their difference, SE, interval, raw and adjusted p-values; study
counts, estimability, reason and method. There is no global p-value.
Its print method invisibly returns the full input object. A stratum_cols
attribute records outcome/time identifiers when present so numeric labels
are preserved during printing.
Explicit method="wald" instead returns the design-test list with
a warning; new code should call network_design_incoherence() directly.
See Also
network_nodesplit(), network_design_incoherence(),
network_heterogeneity(), network_incoherence_plot()
Examples
d <- data.frame(s=1:9,a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3),g=rep(c(.2,.6,.2),3),v=.04)
f <- network_meta(d,"s","a","b","g","v")
network_incoherence(f,adjust="holm")
network_design_incoherence(f)$global
network_heterogeneity(f)$overall
Plot covariance-aware network incoherence assessments
Description
Display descriptive differences, independent node-splitting intervals, or model-based incoherence-test p-values with their calculation labelled.
Usage
network_incoherence_plot(
object,
display = c("difference", "tests", "nodesplit"),
method = c("conditional", "ML", "wald"),
strata = NULL,
ci_level = 0.95,
main = NULL,
adjust = c("none", "holm", "bonferroni"),
estimable_only = FALSE,
point_cex = 1,
label_cex = 0.8
)
Arguments
object |
A fitted joint network model. |
display |
|
method |
|
strata |
Named outcome/time values selecting displayed difference or node-splitting rows. Test displays assess the full model and reject selection. |
ci_level |
Confidence level for descriptive or node-splitting intervals; it does not change test p-values. |
main |
Optional plot title. |
adjust |
Local test or node-split multiplicity adjustment: |
estimable_only |
Logical; for |
point_cex |
Scaling for point markers. |
label_cex |
Scaling for treatment/axis labels. Font family and style
inherit base graphics settings such as |
Details
Descriptive differences. Read direct and indirect GLS summaries from
object$effects, using the original fitted total covariance. Direct evidence
uses supplied rows for the target comparison; indirect evidence removes those
rows, not whole studies. Consequently the summaries can share multi-arm study
information. The displayed difference is direct minus indirect and its SE retains
that cross-covariance. Intervals use the standard normal quantile with
heterogeneity held fixed. This is not formal independent node-splitting.
Independent splits. Call network_nodesplit() and display its
difference, lower and upper. Whole direct-evidence studies are excluded
from the indirect side. Both method choices produce normal Wald intervals;
ML changes heterogeneity estimation, not the interval into a likelihood-ratio
interval. Stratum selection occurs after calculation and does not refit a
stratum-specific model.
Test display. Call network_design_incoherence() and plot the global and
local p-values. conditional uses Wald tests with fitted covariance fixed;
ML uses refitted-ML likelihood-ratio tests. The dashed .05 line is a visual
reference, not an automatic decision rule. Local p-values use the requested
adjustment; the global p-value remains unadjusted.
For difference displays, zero denotes numerical direct/indirect agreement. Positive differences mean larger direct effects on the treatment_2-minus- treatment_1 scale; benefit direction depends on the outcome. Interpret interval width and substantive effect size. Missing evidence is labelled as unavailable; an interval containing zero or a large p-value does not establish transitivity. Diagnostics remain model-based even for a primary CR1 fit.
Value
Invisibly returns the displayed data. difference returns a table of
differences, limits and SEs; nodesplit returns the selected full split table;
tests returns global/local test rows with a comparison label. No fit is altered.
See Also
network_nodesplit(), network_design_incoherence(), network_transitivity().
Examples
d <- data.frame(study=1:9,a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3),effect=rep(c(.2,.6,.2),3),variance=.04)
fit <- network_meta(d,"study","a","b","effect","variance")
network_incoherence_plot(fit,display="nodesplit")
Study or design influence on a joint network fit
Description
Refit after omitting whole studies or all studies with a common treatment design, and summarize the resulting change in treatment estimates.
Usage
network_influence(object, unit = c("study", "design"))
## S3 method for class 'nma_influence_summary'
print(
x,
...,
digits = getOption("digits"),
detailed = FALSE,
row.names = FALSE
)
## S3 method for class 'nma_influence_summary'
summary(object, ..., digits = getOption("digits"), detailed = FALSE)
Arguments
object |
A fitted joint network model; for the summary method, the
summary data frame returned by |
unit |
|
x |
The summary data frame returned by |
... |
Additional arguments passed to |
digits |
Number of decimal places, from 1 to 22.
P-values below 0.0001 print as |
detailed |
Include the stored |
row.names |
Display row names; default |
Details
Omissions remove complete study covariance blocks, preserving alignment of the remaining observations, strata and grouping IDs. The same mean/covariance model is refitted. Heterogeneity is re-estimated unless originally fixed. Predictions are evaluated at every original reported treatment-pair/mean-stratum row, with moderators at the original summary values (normally zero).
For omission g, report
\max_j|\hat d_j^{(-g)}-\hat d_j|, where j ranges over the original
reported treatment comparisons and strata. This is an unstandardized maximum
absolute change on the model's effect scale. It does not summarize changes in
SEs, intervals or heterogeneity; inspect the returned fits to examine those.
It is not Cook's distance, a p-value, or a threshold for study removal. Maximum
changes across differently scaled outcomes need separate interpretation.
Large changes can arise from an informative study, sparse connectivity or a scientifically different design, without indicating an error. Evaluate influence with study quality, clinical relevance and uncertainty. Omissions that disconnect a network, remove a required reference/stratum, make covariance unidentified or fail optimization are flagged. Such failures do not establish incoherence.
Value
A list containing:
- summary
One row per omission with
omitted,unit,estimable,reason, andmax_effect_change.estimablemeans refitting and comparison with all original prediction targets succeeded.- fits
Named list of successfully fitted omission models. A fit can be present even if some original prediction targets could not be evaluated.
- unit
The requested omission unit.
The summary inherits from nma_influence_summary and data.frame. Its
default printout hides estimable while retaining all omission rows and their
reasons. The flag remains accessible as $summary$estimable;
print(result$summary, detailed=TRUE) displays it. Printing changes no data.
No multiple-testing adjustment or automatic study selection is performed.
See Also
network_nodesplit(), network_covariance_sensitivity(),
jackknife_network_meta().
Examples
d <- data.frame(study=1:9,a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3),effect=c(.1,.5,.2,.4,.8,.1,.2,.4,.4),variance=.04)
fit <- network_meta(d,"study","a","b","effect","variance")
network_influence(fit)$summary
network_influence(fit,unit="design")$summary
Create a formatted league table from a fitted network meta-analysis
Description
Create a formatted league table from a fitted network meta-analysis
Usage
network_league_table(
object,
seq = NULL,
ci = TRUE,
backtransf = FALSE,
digits = 2,
text_NA = ".",
bracket = c("[", "]"),
separator = ", "
)
Arguments
object |
A fitted |
seq |
Optional treatment order for rows and columns. |
ci |
Logical; if |
backtransf |
Logical; if |
digits |
Number of decimal places. |
text_NA |
Text used for unavailable cells. |
bracket |
Length-two character vector used around confidence intervals. |
separator |
Separator placed between lower and upper confidence limits. |
Value
A character matrix with one row and column per treatment. For a coherent model with multiple strata, a named list of such matrices.
Examples
network_league_table(nma_fit)
Joint coherent network meta-analysis
Description
All interfaces estimate basic treatment effects jointly under coherence. Standard, multivariate, and multilevel interfaces differ in their random-effect covariance specifications. Sampling covariance is separate from heterogeneity. Incoherence denotes disagreement between evidence sources; transitivity requires substantive assessment of effect modifiers.
Usage
network_meta(
data,
study_id,
treatment_1,
treatment_2,
effect,
variance,
reference = NULL,
model_type = c("coherent", "multivariate", "multilevel", "wls"),
heterogeneity = NULL,
nested_levels = NULL,
moderators = NULL,
estimation_method = "REML",
tau2 = NULL,
control = list(),
ci_level = 0.95,
sampling_covariance = NULL,
observation_id = NULL,
covariance_repair = c("error", "roundoff"),
outcome = NULL,
time = NULL,
treatment_effects = "common",
random_levels = NULL,
inference = "model",
diagnostics = TRUE,
assume_independent = FALSE,
adjust = c("none", "holm", "bonferroni"),
...
)
Arguments
data |
Contrast data, one row per observation. |
study_id, treatment_1, treatment_2, effect, variance |
Column names for study, treatments, effect (treatment_2 minus treatment_1), and sampling variance. |
reference |
Network reference treatment; defaults to first sorted label.
It need not occur in every study. Supplied basic-effect covariance must use
this reference's coordinates. Printed models and summaries show treatment
minus reference contrasts by default. Use |
model_type |
|
heterogeneity |
One of |
nested_levels |
Ordered grouping columns nested within study. IDs are
combined with their parents. Use |
moderators |
Numeric column names or a one-sided formula without an intercept; categorical variables are expanded by model.matrix. Covariates interact with basic treatment effects. Effects are reported at covariate zero. |
estimation_method |
ML or REML; MLE is accepted as ML. |
tau2 |
Fixed nonnegative variance(s), or a named basic-effect covariance matrix in the requested reference/stratum coordinates. NULL estimates variance. |
control |
List with |
ci_level |
Confidence level. |
sampling_covariance |
Named full matrix or named study blocks. With NULL, sampling errors are independent. Covariance dimension names are observation IDs. |
observation_id |
Column of unique observation IDs. Defaults to row numbers. |
covariance_repair |
|
outcome, time |
Optional columns defining outcome and time strata. |
treatment_effects |
One of |
random_levels |
Optional grouping columns for additional signed treatment random effects within studies. Crossed groups are allowed. Each group adds one common contrast variance; IDs are interpreted within study. |
inference |
|
diagnostics |
Compute design-by-treatment Wald incoherence tests with heterogeneity refitted by REML under the augmented model. |
assume_independent |
Explicitly assume independent sampling errors for multiple observations within a study when covariance is unavailable. FALSE requires sampling covariance for such studies. |
adjust |
Multiplicity adjustment for total treatment-effect p-values:
|
... |
Reserved for future arguments; unknown arguments are rejected. |
Details
Printing includes network counts, model settings and sampling-only residual Q/I-squared summaries. See network_model_summary for their definitions.
Multiplicity adjustment is performed after fitting using stats::p.adjust().
Each two-sided p-value tests a total network treatment contrast against zero,
using the fitted standard error and the model's normal or CR1 t reference
distribution. Contrasts with moderators are evaluated at covariate zero.
Holm and Bonferroni control family-wise error when the individual tests are
valid; they accommodate dependence among treatment comparisons. The family
includes indirectly estimated pairs and is independent of the network reference.
Its size is the number of rows in effects; nonestimable p-values remain NA
and their hypotheses are retained in the family size.
effects$total_p_value contains raw p-values and
effects$total_p_adjusted contains adjusted p-values. adjustment records
the method, family description and size. Estimates, standard errors and
heterogeneity are unchanged. All existing confidence intervals remain
pointwise at ci_level: Holm or Bonferroni p-value adjustment does not turn
them into simultaneous intervals. Adjusted p-values can therefore disagree
with whether a pointwise interval excludes zero. Adjustment does not cover
moderator-coefficient tests, direct/indirect tests or incoherence diagnostics.
Value
An nma_coherent / nma_mars object with a shared result structure.
References
Lu, G., and Ades, A. E. (2004). Combination of direct and indirect evidence in mixed treatment comparisons. Statistics in Medicine, 23(20), 3105–3124. doi:10.1002/sim.1875.
Higgins, J. P. T., Jackson, D., Barrett, J. K., Lu, G., Ades, A. E., and White, I. R. (2012). Consistency and inconsistency in network meta-analysis: concepts and models for multi-arm studies. Research Synthesis Methods, 3, 98–110. doi:10.1002/jrsm.1044.
White, I. R., Barrett, J. K., Jackson, D., and Higgins, J. P. T. (2012). Consistency and inconsistency in network meta-analysis: model estimation using multivariate meta-regression. Research Synthesis Methods, 3, 111–125. doi:10.1002/jrsm.1045.
White, I. R. (2015). Network meta-analysis. The Stata Journal, 15(4), 951–985. doi:10.1177/1536867X1501500403.
Examples
d <- data.frame(study=1:6, a=c("A","A","B","A","A","B"),
b=c("B","C","C","B","C","C"),
effect=c(.2,.5,.3,.3,.6,.2), variance=.04)
network_meta(d,"study","a","b","effect","variance",reference="A")
One-stage coherent network meta-analysis
Description
Fits a Gaussian contrast likelihood with separate sampling and heterogeneity covariance. Effects are treatment_2 minus treatment_1. Studies are independent. The default is common-effect GLS; common heterogeneity induces equal pairwise heterogeneity variances and coherent multi-arm random effects.
Usage
network_meta_coherent(
data,
study_id,
treatment_1,
treatment_2,
effect,
variance,
reference = NULL,
heterogeneity = c("none", "common", "unstructured"),
sampling_covariance = NULL,
observation_id = NULL,
covariance_repair = c("error", "roundoff"),
outcome = NULL,
time = NULL,
treatment_effects = c("common", "by_outcome", "by_time", "by_outcome_time"),
moderators = NULL,
random_levels = NULL,
tau2 = NULL,
estimation_method = "REML",
inference = c("model", "CR1"),
diagnostics = TRUE,
ci_level = 0.95,
control = list(),
assume_independent = FALSE,
adjust = c("none", "holm", "bonferroni")
)
## S3 method for class 'nma_coherent'
predict(
object,
newdata,
se.fit = FALSE,
interval = c("none", "confidence", "prediction"),
level = 0.95,
new_levels = c("study", object$random_levels),
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
...
)
Arguments
data |
Contrast data, one row per observation. |
study_id, treatment_1, treatment_2, effect, variance |
Column names for study, treatments, effect (treatment_2 minus treatment_1), and sampling variance. |
reference |
Network reference treatment; defaults to first sorted label.
It need not occur in every study. Supplied basic-effect covariance must use
this reference's coordinates. Printed models and summaries show treatment
minus reference contrasts by default. Use |
heterogeneity |
One of |
sampling_covariance |
Named full matrix or named study blocks. With NULL, sampling errors are independent. Covariance dimension names are observation IDs. |
observation_id |
Column of unique observation IDs. Defaults to row numbers. |
covariance_repair |
|
outcome, time |
Optional columns defining outcome and time strata. |
treatment_effects |
One of |
moderators |
Numeric covariate column names; effects are treatment interactions. |
random_levels |
Optional grouping columns for additional signed treatment random effects within studies. Crossed groups are allowed. Each group adds one common contrast variance; IDs are interpreted within study. |
tau2 |
Fixed nonnegative variance(s), or a named basic-effect covariance matrix in the requested reference/stratum coordinates. NULL estimates variance. |
estimation_method |
ML or REML; MLE is accepted as ML. |
inference |
|
diagnostics |
Compute design-by-treatment Wald incoherence tests with heterogeneity refitted by REML under the augmented model. |
ci_level |
Confidence level. |
control |
List with |
assume_independent |
Explicitly assume independent sampling errors for multiple observations within a study when covariance is unavailable. FALSE requires sampling covariance for such studies. |
adjust |
|
object |
A fitted joint network model. |
newdata |
Prediction treatment pairs, strata and covariates. |
se.fit |
Return standard errors. |
interval |
None, confidence, or prediction for a true treatment contrast.
Prediction-interval data frames use the compact display documented in
|
level |
Prediction/confidence coverage. |
new_levels |
Grouping levels contributing variance for new random units. Omitted levels are fixed at zero; this is not a conditional BLUP prediction. |
... |
Reserved prediction arguments. |
Details
Printed results include network counts, model settings and sampling-only Q/I-squared summaries. See network_model_summary for count definitions, diagnostic interpretation and reference/all-pair display selection.
Computational safeguards. Observation IDs must be unique and match
covariance dimension names. The supplied covariance diagonal must agree with
the variance column; variances must be finite and positive. Covariance is checked
for symmetry, positive semidefiniteness and absence of cross-study dependence.
The likelihood also rejects singular or numerically near-singular sampling
covariance: redundant contrasts require a justified independent basis, not
artificial diagonal noise. covariance_repair="roundoff" clips only tiny
negative eigenvalues; it does not permit materially invalid or singular input.
The treatment/moderator design must have full column rank. A failure can indicate disconnected treatments or nonestimable mean strata/interactions. Before estimating heterogeneity, the covariance-kernel derivatives must be linearly independent, and residual observations must remain after estimating the means. These checks establish numerical/structural estimability, not precision of covariance estimates.
Inspect convergence$code, convergence$message, and convergence$boundary.
Boundary flags mean a variance or covariance eigenvalue is near zero; this may
be a supported zero-variance solution or weak information, rather than an error.
Optimization success and valid input covariance do not establish transitivity,
coherence of evidence, or correct scientific dependence assumptions. Use
network_transitivity(), network_incoherence(), network_nodesplit(), and
network_covariance_sensitivity() for the complementary assessments.
Value
An nma_coherent object also inheriting from nma_mars, with aligned
sampling covariance, fitted covariance, coefficients, contrasts, and diagnostics.
$design_incoherence contains cached design-by-treatment tests when requested.
$incoherence retains the same design-test list for compatibility; use
network_incoherence() explicitly for independent direct/indirect splits.
References
Lu, G., and Ades, A. E. (2004). Combination of direct and indirect evidence in mixed treatment comparisons. Statistics in Medicine, 23(20), 3105–3124. doi:10.1002/sim.1875.
Higgins, J. P. T., Jackson, D., Barrett, J. K., Lu, G., Ades, A. E., and White, I. R. (2012). Consistency and inconsistency in network meta-analysis: concepts and models for multi-arm studies. Research Synthesis Methods, 3, 98–110. doi:10.1002/jrsm.1044.
White, I. R., Barrett, J. K., Jackson, D., and Higgins, J. P. T. (2012). Consistency and inconsistency in network meta-analysis: model estimation using multivariate meta-regression. Research Synthesis Methods, 3, 111–125. doi:10.1002/jrsm.1045.
White, I. R. (2015). Network meta-analysis. The Stata Journal, 15(4), 951–985. doi:10.1177/1536867X1501500403.
Examples
dat <- data.frame(study = 1:6, a = rep(c("A", "A", "B"), 2),
b = rep(c("B", "C", "C"), 2),
yi = c(.2, .5, .3, .3, .6, .4), vi = .04)
fit <- network_meta_coherent(dat, "study", "a", "b", "yi", "vi")
coef(fit)
Repeated-effects network meta-analysis from arm-level continuous data
Description
Fits a treatment-design network meta-analysis to arm-level continuous data while constructing multi-arm, outcome, and repeated-time sampling covariance internally, then uses the shared joint network likelihood.
Usage
network_meta_repeated(
data,
study_id,
treatment,
mean,
sd,
n,
outcome = NULL,
time = NULL,
reference = NULL,
treatment_effects = c("common", "by_outcome", "by_time", "by_outcome_time"),
outcome_correlation = c("independence", "exchangeable"),
time_correlation = c("independence", "exchangeable", "ar1"),
rho_outcome = 0,
rho_time = 0,
heterogeneity = c("none", "common"),
estimation_method = c("REML", "ML"),
ci_level = 0.95,
measure = c("MD", "SMD"),
standardizer = "pair_pooled",
arm_observation_id = NULL,
correlations = NULL,
overlap = NULL,
assume_independent = FALSE,
adjust = c("none", "holm", "bonferroni")
)
Arguments
data |
Data frame with one row per study, treatment arm, outcome, and optional time combination. |
study_id, treatment, mean, sd, n |
Character strings naming study, treatment, arm mean, arm standard deviation, and arm sample-size columns. |
outcome, time |
Optional character strings identifying outcomes and follow-up occasions. Omit either when it is not present. |
reference |
Optional reference treatment. Defaults to the first sorted treatment. |
treatment_effects |
Whether treatment effects are common, outcome specific, time specific, or outcome-by-time specific. |
outcome_correlation, time_correlation |
Correlation structures used to
construct covariance among means from the same arm. |
rho_outcome, rho_time |
Correlations for exchangeable or AR(1) structures. Values must be between minus one and one. |
heterogeneity |
Either |
estimation_method |
Either |
ci_level |
Confidence level for coefficient intervals. |
measure |
|
standardizer |
SMD denominator definition passed to |
arm_observation_id |
Unique arm measurement ID column for SMD covariance. |
correlations, overlap |
Named study matrices for SMD individual correlations
and participant overlap; see |
assume_independent |
Explicit independent-measurement assumption for SMDs. |
adjust |
|
Details
The function currently supports arm-level continuous mean
differences. Multi-arm covariance is derived exactly under independent arms.
Outcome and time covariance are derived from the chosen correlation
assumptions; these assumptions are retained in the fitted object. For time
correlation "ar1", equally spaced ordered occasions are assumed unless
time is numeric, in which case correlation is rho_time raised to the
absolute time distance. Heterogeneity uses coherent signed treatment contrasts.
Value
An object of class nma_repeated_mars containing the derived
contrast data, internally constructed study covariance blocks, coefficient
summary, fitted covariance, and heterogeneity estimate.
References
Higgins, J. P. T., Jackson, D., Barrett, J. K., Lu, G., Ades, A. E., and White, I. R. (2012). Consistency and inconsistency in network meta-analysis: concepts and models for multi-arm studies. Research Synthesis Methods, 3, 98–110. doi:10.1002/jrsm.1044.
White, I. R., Barrett, J. K., Jackson, D., and Higgins, J. P. T. (2012). Consistency and inconsistency in network meta-analysis: model estimation using multivariate meta-regression. Research Synthesis Methods, 3, 111–125. doi:10.1002/jrsm.1045.
Examples
dat <- data.frame(
study = rep(c("S1", "S2", "S3"), each = 2),
trt = rep(c("A", "B"), 3), mean = c(10, 12, 9, 11, 11, 14),
sd = 2, n = 30
)
network_meta_repeated(dat, "study", "trt", "mean", "sd", "n")
Print and summarize joint network models
Description
Display treatment effects against the fitted reference by default, with an explicit option for all pairwise comparisons.
Usage
## S3 method for class 'nma_coherent'
print(
x,
...,
comparisons = c("reference", "all"),
digits = getOption("digits"),
detailed = FALSE
)
## S3 method for class 'nma_coherent'
summary(
object,
...,
comparisons = c("reference", "all"),
digits = getOption("digits"),
detailed = FALSE,
inference = NULL,
test = NULL,
robust_type = NULL,
cluster = NULL,
hksj_adjust = NULL,
level = NULL
)
Arguments
x, object |
A fitted |
... |
Reserved additional print or summary arguments. |
comparisons |
|
digits |
Number of decimal places to display, an integer from 1 to
22. Defaults to |
detailed |
Logical; show the complete coefficient table as well as the
selected treatment contrasts. Defaults to |
inference |
Optional summary-only |
test |
Optional summary-only coefficient/total-contrast test: |
robust_type |
Optional summary-only sandwich covariance, e.g. CR2. |
cluster |
Optional fitted contrast-data cluster column, default study_id. |
hksj_adjust |
Unsupported for networks; supplied values raise an error. |
level |
Optional summary-only coefficient/total-contrast confidence level. |
Details
Printed treatment comparisons have a contrast label of treatment_2 minus
treatment_1 (for example, Metformin - Placebo). Stored treatment identifiers
and estimates retain their original structure.
Reference display sets treatment_1 to the fitted reference and treatment_2 to
the other treatment. Estimates are negated and interval endpoints reversed
when the stored contrast has the opposite direction. Standard errors and
p-values are unchanged. Coefficients and variance summaries are displayed as
fitted. Moderator-zero evaluation and stratum definitions are unchanged.
Basic treatment coefficients reproduce the reference contrasts at moderator
zero. The default display therefore shows treatment results once, as contrasts.
For moderator models, additional interaction coefficients are displayed in a
separate table. detailed=TRUE restores all basic and moderator coefficients.
Treatment contrasts include statistic = estimate / SE; its reference
distribution (normal or t with the fitted df) is stated in the model settings.
Display selection does not refit the model or restrict $effects, league
tables, confidence-interval methods, or incoherence diagnostic hypotheses.
Multiplicity-adjusted p-values retain the original fitted family, including
comparisons omitted from the display. This is not an adjustment over only
reference comparisons.
summary(object, comparisons="all") records the display choice on the returned
copy. An explicit print(..., comparisons=) overrides that choice. The input
fitted object is unchanged.
Network counts use analyzed studies and their full treatment sets. Pairwise
comparisons count each unordered pair once per study, including multi-arm
comparisons implied by an independent contrast basis. Unique treatment pairs
count those pairs once across studies. Repeated outcomes/times do not create
additional studies or duplicate study pairs. Modeled contrast rows count the
actual analyzed rows; they may be correlated. Designs are unique study
treatment sets. Counts are independent of the reference and display selection.
Residual variation uses network_q_decomposition(): sampling-covariance GLS
overall, within-design and between-design Q with residual/rank-increase df.
Overall Q reflects both within-design heterogeneity and between-design
incoherence. Q-based I-squared is 100 * max(0, 1 - df / Q) for the overall
and within-design components when df is positive; Q=0 gives zero. With zero
df it is unavailable, not zero. Between-design I-squared is not reported.
These I-squared values are not additive, do not partition multivariate or
multilevel variance components, and do not use fitted random-effect covariance.
Shared moderators remain in the mean model, so these are residual diagnostics.
The random-effects Higgins design test is a separate assessment. Numerical
failure of the sampling-only calculation is labelled unavailable and does not
prevent printing the fitted model.
Summary-only inference='model' or inference='robust' can select
model normal, expected-information Satterthwaite, or cluster-robust inference.
Model Satterthwaite requires converged interior estimated heterogeneity.
HKSJ is unsupported. These overrides affect basic coefficients and total
treatment contrasts only; all other calculations retain the fitted settings.
Value
print() invisibly returns its input. summary() returns the fitted
object with display_comparisons, display_digits and display_detailed attributes for subsequent printing; its
complete model results and classes are retained.
See Also
network_meta_coherent(), network_league_table(), confint.nma_coherent(),
mars_inference_options for the model compatibility and argument tables.
Examples
d <- data.frame(s=1:9,a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3),g=rep(c(.2,.6,.2),3),v=.04)
fit <- network_meta_coherent(d,"s","a","b","g","v",reference="B")
print(fit)
summary(fit, comparisons="all")
print(fit, comparisons="all")
summary(fit, digits=3)
print(summary(fit, digits=3), digits=5)
summary(fit, detailed=TRUE)
print(summary(fit, detailed=TRUE), detailed=FALSE)
Independent direct and indirect evidence by node-splitting
Description
Estimate a direct-minus-indirect treatment difference using separate study allocation, with explicit handling of multi-arm trials and nonestimable splits.
Usage
network_nodesplit(
object,
method = c("conditional", "ML"),
comparisons = NULL,
level = 0.95,
adjust = c("none", "holm", "bonferroni")
)
Arguments
object |
A fitted joint network model. |
method |
|
comparisons |
Optional data frame with |
level |
Coverage of pointwise normal-approximation intervals for direct effects, indirect effects and their difference. |
adjust |
|
Details
For each pair and mean stratum, construct one direct contrast per eligible study from its observed contrast basis using sampling-covariance-aware GLS weights. The target contrast must be estimable within that study/stratum. Thus a three-arm study contributes direct B/C evidence even if its supplied rows are A/B and A/C. Moderators must be constant within each direct study/stratum; reported effects are evaluated at moderator zero, as in the original model.
Every study containing both target treatments in the target stratum is excluded from the indirect side, including all its other outcomes or times. Remaining studies must identify an indirect treatment contrast. This is conservative whole-study allocation: it can discard otherwise useful evidence in other strata, but prevents the same multi-arm study from providing both direct and indirect evidence. A network containing only A/B/C trials supplies no independent indirect route for those pairs after allocation.
A linear transformation T creates the direct study contrasts and retains the
indirect observations. Effects, sampling covariance, random-effect design and
covariance kernels transform as Ty, TST^T, and their corresponding
matrix products. A direct-evidence mean indicator is added to the transformed
network model. The conditional method uses transformed fitted total covariance;
ML estimates heterogeneity jointly in that split model unless originally fixed.
The latter uses a shared covariance specification, rather than fitting unrelated
heterogeneity models separately on the two sides.
For a returned pair, all effects are treatment_2 minus treatment_1. Compute
\Delta=\hat d_{direct}-\hat d_{indirect} and
SE(\Delta)^2=SE(\hat d_{direct})^2+SE(\hat d_{indirect})^2-
2\operatorname{Cov}(\hat d_{direct},\hat d_{indirect}).
Direct and indirect intervals are each estimate plus or minus
z_{(1+level)/2} times its own SE. Difference intervals are
\Delta\mathbin{\pm}z_{(1+level)/2}SE(\Delta); the two-sided
p-value is the standard normal Wald test of \Delta=0. Even with ML, this
p-value is not a likelihood-ratio test. Covariance estimates are treated as fixed
for interval calculation, and primary CR1 inference is not propagated.
A positive difference means the direct numerical effect exceeds the indirect
one. Whether that favors a treatment depends on outcome and benefit direction.
For logarithmic ratios, exponentiating the difference gives the ratio of the
direct and indirect ratio estimates, not a pooled treatment effect. Inspect the
magnitude and interval on the substantive effect scale, not only the p-value.
An interval containing zero does not establish coherence. Pair/stratum tests
are not multiplicity adjusted unless adjust is supplied.
Value
One row per selected pair/mean stratum, including:
- network, network_se
Coherent-model estimate and model-based SE in the same treatment_2-minus-treatment_1 direction.
- prop
Direct evidence proportion: coherent-model variance divided by direct-only variance, both evaluated at the primary fitted covariance. It describes precision contribution, not the fraction of studies or patients. It remains on the primary covariance scale even for ML splits. Missing when direct precision is unavailable or no valid proportion can be formed.
- z
Signed normal Wald statistic: difference divided by its SE.
- direct, indirect, direct_se, indirect_se
Split mean effects and model-based standard errors.
- direct_lower, direct_upper, indirect_lower, indirect_upper
Pointwise normal confidence limits at
levelfor each evidence estimate. Direct limits remain available when the indirect route is not estimable.- direct_indirect_covariance
Covariance used in the difference variance.
- difference, se, lower, upper, p_value
Direct-minus-indirect estimate, its SE, normal interval and two-sided Wald p-value.
- direct_studies
Number of studies furnishing an estimable direct contrast.
- indirect_studies
Number of all retained indirect-side studies, including studies in other strata; not necessarily the number on a particular path.
- estimable, reason, method
Eligibility/status and calculation. A direct estimate may be available even when an independent split is not estimable.
Failure reasons include unavailable independent indirect evidence, aliased mean
parameters, nonidentifiable covariance or failed optimization. Missing split
results are not nonsignificant results. The returned allocation and inference
attributes describe study allocation and inference assumptions.
References
Dias, S., Welton, N. J., Caldwell, D. M., and Ades, A. E. (2010). Checking consistency in mixed treatment comparison meta-analysis. Statistics in Medicine, 29(7–8), 932–944. doi:10.1002/sim.3767.
van Valkenhoef, G., Dias, S., Ades, A. E., and Welton, N. J. (2016). Automated generation of node-splitting models for assessment of inconsistency in network meta-analysis. Research Synthesis Methods, 7(1), 80–93. doi:10.1002/jrsm.1167.
See Also
network_nodesplit_plot(), network_incoherence(), network_incoherence_plot(),
network_transitivity(), network_influence().
Examples
d <- data.frame(study=1:9,a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3),effect=rep(c(.2,.6,.2),3),variance=.04)
fit <- network_meta(d,"study","a","b","effect","variance")
network_nodesplit(fit,comparisons=data.frame(treatment_1="A",treatment_2="B"))
# A/B: direct .2, indirect .6 - .2 = .4, difference -.2.
Plot direct and indirect node-split effects side by side
Description
Display independently allocated direct and indirect evidence estimates with separate pointwise confidence intervals and numerical columns.
Usage
network_nodesplit_plot(
object,
method = c("conditional", "ML"),
comparisons = NULL,
level = 0.95,
adjust = c("none", "holm", "bonferroni"),
strata = NULL,
main = "Direct and indirect node-split effects",
estimable_only = FALSE,
point_cex = 1,
label_cex = 0.8
)
Arguments
object |
A fitted joint network model. |
method |
|
comparisons |
Optional data frame with |
level |
Coverage of pointwise normal-approximation intervals for direct effects, indirect effects and their difference. |
adjust |
|
strata |
Named list selecting fitted outcome/time strata for display. Adjustment uses all requested comparisons before this display selection. |
main |
Plot title. |
estimable_only |
Logical; omit unavailable splits from the figure
(default |
point_cex |
Scaling for point markers. |
label_cex |
Scaling for treatment/axis labels. Font family and style
inherit base graphics settings such as |
Details
Calls network_nodesplit() and plots treatment_2 minus treatment_1 for each
pair/stratum. The direct and indirect series use separate symbols and vertical
offsets on a shared effect axis. Unavailable evidence is labelled not estimable;
an available direct estimate is still shown when an indirect route is absent.
Intervals are model-based normal intervals, conditional on the fitted covariance
or the jointly refitted ML covariance. adjust changes the difference-test
p-values in the returned table, not these pointwise intervals. Interval overlap
is not the direct-minus-indirect Wald test: use the returned difference interval
and p-value, which retain direct-indirect covariance.
These whole-study node splits differ from the descriptive conditional GLS
summaries displayed by network_forest_overlay_plot(). For a plot of the
direct-minus-indirect difference, use network_incoherence_plot() with
display="nodesplit".
Value
Invisibly returns the selected node-split table, including confidence limits, adjusted p-values, estimability and failure reasons.
See Also
network_nodesplit(), network_incoherence_plot()
Examples
d <- data.frame(s=1:9,a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3),g=rep(c(.2,.6,.2),3),v=.04)
fit <- network_meta(d,"s","a","b","g","v")
network_nodesplit_plot(fit,adjust="holm")
Print network diagnostic tables without rounding stored results
Description
Used by descriptive transitivity, heterogeneity-profile and asymmetry tables.
Usage
## S3 method for class 'nma_output_table'
print(x, ..., digits = getOption("digits"), row.names = FALSE)
## S3 method for class 'nma_output_table'
summary(object, ..., digits = getOption("digits"))
Arguments
x, object |
A network diagnostic table. |
... |
Additional arguments passed to |
digits |
Decimal places, an integer from 1 to 22. P-values below 0.0001
print as |
row.names |
Display row names (default |
Value
print() invisibly returns its input. summary() returns the table
with the requested precision remembered; numerical values are unchanged.
Convert arm-level study data to contrast-level network meta-analysis data
Description
Convert arm-level study data to contrast-level network meta-analysis data
Usage
network_pairwise_data(
data,
study_id,
treatment,
event = NULL,
n = NULL,
mean = NULL,
sd = NULL,
effect_measure = c("OR", "RR", "RD", "MD"),
continuity = 0.5
)
Arguments
data |
Arm-level data frame. |
study_id, treatment |
Column names for study and treatment labels. |
event, n |
Column names for binary events and sample sizes. |
mean, sd |
Column names for continuous means and standard deviations. |
effect_measure |
One of |
continuity |
Continuity correction for binary log odds/risk ratios with zero cells. |
Details
Returns a nonredundant baseline contrast basis. The study covariance
blocks are stored in the sampling_covariance attribute and used automatically
by network_meta(). Subset/reorder covariance together with observations.
Value
A contrast-level data frame with observation IDs and columns study,
treatment_1, treatment_2, effect, and variance.
Examples
arm_dat <- data.frame(
study = c("S1", "S1", "S2", "S2"),
treatment = c("A", "B", "A", "C"),
events = c(10, 14, 12, 9),
n = c(100, 100, 90, 95)
)
network_pairwise_data(
arm_dat,
study_id = "study",
treatment = "treatment",
event = "events",
n = "n",
effect_measure = "OR"
)
Export a network plot at explicit publication dimensions
Description
Export a network plot at explicit publication dimensions
Usage
network_plot_export(
plot,
file,
width = 10,
height = 7,
dpi = 300,
family = "sans"
)
Arguments
plot |
A zero-argument function that draws the plot. |
file |
Output filename ending in pdf, png, or svg. |
width, height |
Device dimensions in inches. |
dpi |
PNG resolution. |
family |
Font family, default |
Value
Invisibly returns the output filename. The device is closed on errors.
Examples
dat <- data.frame(study = 1:6, a = rep(c("A", "A", "B"), 2),
b = rep(c("B", "C", "C"), 2),
yi = c(.2, .5, .3, .3, .6, .4), vi = .04)
fit <- network_meta(dat, "study", "a", "b", "yi", "vi")
path <- tempfile(fileext = ".pdf")
network_plot_export(function() network_rank_plot(fit, "higher", nsim = 500), path)
file.exists(path)
unlink(path)
Prediction intervals for all network treatment contrasts
Description
Prediction intervals for all network treatment contrasts
Usage
network_prediction_intervals(object, level = 0.95)
## S3 method for class 'nma_prediction_intervals'
print(
x,
...,
digits = getOption("digits"),
detailed = FALSE,
row.names = FALSE
)
## S3 method for class 'nma_prediction_intervals'
summary(object, ..., digits = getOption("digits"), detailed = FALSE)
Arguments
object |
A fitted |
level |
Prediction interval level. |
x |
A prediction-interval result. |
... |
Additional arguments forwarded to |
digits |
Number of decimal places, from 1 to 22.
P-values below 0.0001 print as |
detailed |
Show all stored columns instead of the compact display. |
row.names |
Display data-frame row names; default |
Details
tau2_prediction is the variance added for the selected new random
units. It can vary by contrast or stratum, particularly with unstructured
heterogeneity. It is collapsed only when exactly equal in every row, before
display rounding. Prediction intervals describe true effects in new random
units, not individual patient outcomes. summary(x, digits=) records display
precision without modifying numerical results.
Value
A data frame with total network effects, standard errors, the
between-study variance used for prediction, and prediction interval bounds.
It inherits from nma_prediction_intervals and data.frame. The default
printout shows the contrast, mean-effect SE, prediction SE and interval.
Shared prediction targets, prediction variances and degrees of freedom are
printed once above the rows; varying values remain in columns. All original
columns and full precision are retained. print(x, detailed=TRUE) shows
every stored column, including alternate names for interval bounds.
The same display applies to coherent-model predict(..., interval="prediction").
Examples
network_prediction_intervals(nma_fit)
Plot the full distribution of network treatment ranks
Description
Plot the full distribution of network treatment ranks
Usage
network_rank_plot(
object,
benefit_direction,
strata = NULL,
nsim = 10000L,
seed = 1L,
main = "Treatment rank probabilities",
colors = c("#F7FBFF", "#0072B2"),
type = c("heatmap", "bar"),
label_cex = 0.8,
value_cex = 0.8
)
Arguments
object |
A fitted network model; for the ranking-table summary method,
the |
benefit_direction |
Whether |
strata |
Named outcome/time selection; exactly one stratum is required. |
nsim |
Number of draws, at least 100. |
seed |
Optional local seed; the caller's random-number state is restored. |
main |
Plot title. |
colors |
Heatmap palette; the last color is used for bar rankograms. |
type |
|
label_cex |
Scaling for treatment/axis labels. Font family and style
inherit base graphics settings such as |
value_cex |
Scaling for heatmap probability labels. |
Details
Both displays use the same joint simulations and return the same ranking object. The heatmap shows rank 1 on the left, treatments ordered by mean rank (best average position first), a fixed 0–1 color scale and rounded percentage labels. Bar panels show rank on the horizontal axis and its probability on the vertical axis, with treatments in the same mean-rank order. Each panel sums to one for continuous draws without ties. A sharply concentrated distribution indicates a more certain rank under this model; a broad or multi-peaked distribution is hidden by a single SUCRA summary. These plots concern ranks of average effects, not effect magnitudes, clinical relevance or new-study predictions. Zero-percent heatmap labels can represent small nonzero probabilities after rounding.
Value
Invisibly returns the ranking calculation, including benefit direction.
References
Rücker, G., and Schwarzer, G. (2015). Ranking treatments in frequentist network meta-analysis works without resampling methods. BMC Medical Research Methodology, 15, 58. doi:10.1186/s12874-015-0060-8.
Salanti, G., Ades, A. E., and Ioannidis, J. P. A. (2011). Graphical methods and numerical summaries for presenting results from multiple-treatment meta-analysis: an overview and tutorial. Journal of Clinical Epidemiology, 64, 163–171. doi:10.1016/j.jclinepi.2010.03.016.
See Also
network_rankings() for joint simulation and ranking definitions.
Examples
dat <- data.frame(study = 1:6, a = rep(c("A", "A", "B"), 2),
b = rep(c("B", "C", "C"), 2),
yi = c(.2, .5, .3, .3, .6, .4), vi = .04)
fit <- network_meta(dat, "study", "a", "b", "yi", "vi")
network_rank_plot(fit, benefit_direction = "higher", nsim = 500)
Recalculate network rankings with an explicit benefit direction
Description
Rankings use a multivariate normal approximation to the fitted coefficient distribution. They describe uncertainty in average effects, not new-study outcomes. Rank 1 is best under the specified direction. Interpret rankings alongside effect estimates and intervals, not probability of best alone.
Usage
network_rankings(
object,
benefit_direction,
strata = NULL,
nsim = 10000L,
seed = 1L
)
## S3 method for class 'nma_ranking_table'
print(
x,
...,
digits = getOption("digits"),
detailed = FALSE,
row.names = FALSE
)
## S3 method for class 'nma_ranking_table'
summary(object, ..., digits = getOption("digits"), detailed = FALSE)
Arguments
object |
A fitted network model; for the ranking-table summary method,
the |
benefit_direction |
Whether |
strata |
Named outcome/time selection; exactly one stratum is required. |
nsim |
Number of draws, at least 100. |
seed |
Optional local seed; the caller's random-number state is restored. |
x |
A ranking table from |
... |
Additional arguments passed to |
digits |
Decimal places, from 1 to 22. P-values below 0.0001 print as
|
detailed |
Display the duplicate output name |
row.names |
Display row names (default |
Details
Joint Gaussian draws. For the selected stratum, form basic effects
relative to the reference at moderator zero. If their prediction design is
X_b, use \hat b=X_b\hat\beta and the full covariance
V_b=X_b\operatorname{Var}(\hat\beta)X_b^T. Draw
b^{(s)}\sim N(\hat b,V_b) and set the reference-relative effect to zero.
The zero reference is a coordinate choice, not an error-free absolute treatment
effect. Draws use an eigen-based covariance square root; negative eigenvalues
are truncated to zero. Treatment effects are not sampled independently.
Covariance and conditioning. Joint fits use object$fit$vcov, including
CR1 covariance when selected. Rank sampling still uses a multivariate normal
approximation for CR1 fits, not a multivariate t distribution. Heterogeneity
remains at its fitted value; draws do not re-estimate variance components or
propagate their estimation uncertainty. Multiplicity-adjusted treatment
p-values do not change this ranking distribution.
Direction and summaries. Rank 1 is best: sort ascending for lower
and descending for higher, using average ranks for ties. mean_rank and
median_rank summarize draws. p_best and the rank_probability matrix are
on the 0–1 scale. sucra (also sucr_a) is on the 0–100 percentage scale:
100\{K-\overline R_i\}/(K-1), where K is the treatment count.
sucr_a is an duplicate output name, hidden by default when printing
the ranking table. Use detailed=TRUE to display it. Each row
of rank_probability gives the probabilities of ranks 1 through K for one
treatment; its first column equals that treatment's p_best. Rows sum to one
for continuous draws without ties. These probabilities are comparable in
meaning to the probabilities printed by a netmeta rankogram.
sucra is simulated, not an analytic P-score; repeated seeds/draw counts can
assess Monte Carlo stability. seed is local and restores the caller's RNG
state; seed=NULL uses and advances that state.
Why preserve covariance? Contrast uncertainty is
\operatorname{Var}(d_i-d_j)=V_{ii}+V_{jj}-2V_{ij}. Independent treatment
draws are equivalent only when they preserve the relevant contrast distribution.
For a continuous Gaussian distribution and lower-is-better effects, fractional
expected SUCRA is
\frac{1}{K-1}\sum_{j\ne i}
\Phi\!\left(\frac{\hat d_j-\hat d_i}{\sqrt{\operatorname{Var}(d_i-d_j)}}\right).
This equals the corresponding Gaussian P-score computed from the same contrast means and SEs; finite simulated SUCRA has Monte Carlo error. Probability of being best and full rank distributions require a compatible joint distribution. Interpret rankings together with effect sizes and intervals; high SUCRA does not demonstrate a clinically important advantage or establish transitivity.
Value
Ranking summaries, a rank-probability matrix, and direction metadata.
References
Rücker, G., and Schwarzer, G. (2015). Ranking treatments in frequentist network meta-analysis works without resampling methods. BMC Medical Research Methodology, 15, 58. doi:10.1186/s12874-015-0060-8.
Salanti, G., Ades, A. E., and Ioannidis, J. P. A. (2011). Graphical methods and numerical summaries for presenting results from multiple-treatment meta-analysis: an overview and tutorial. Journal of Clinical Epidemiology, 64, 163–171. doi:10.1016/j.jclinepi.2010.03.016.
See Also
network_rank_plot(), network_meta(), confint.nma_coherent()
Examples
dat <- data.frame(study = 1:6, a = rep(c("A", "A", "B"), 2),
b = rep(c("B", "C", "C"), 2),
yi = c(.2, .5, .3, .3, .6, .4), vi = .04)
fit <- network_meta(dat, "study", "a", "b", "yi", "vi")
network_rankings(fit, benefit_direction = "higher", nsim = 500)$rankings
Construct dependent Hedges SMDs from arm summaries
Description
Uses a joint first-order delta method under multivariate normal measurements, independent randomized arms, and fixed sample sizes. Sampling covariance includes both numerator and estimated-denominator uncertainty. This is an approximation, not an exact finite-sample covariance formula. Pair-pooled SDs assume a common population SD for interpretation on an additive network scale; unequal population SDs can violate that interpretation. A control SD is tied to the chosen baseline.
Usage
network_smd_data(
data,
study_id,
treatment,
mean,
sd,
n,
outcome = NULL,
time = NULL,
arm_observation_id = NULL,
standardizer = c("pair_pooled", "study_pooled", "control_sd"),
correction = TRUE,
correlations = NULL,
overlap = NULL,
assume_independent = FALSE,
all_contrasts = FALSE
)
Arguments
data |
Arm-level data, one row per study/treatment/outcome/time. |
study_id, treatment, mean, sd, n |
Column names for study, arm, mean, SD, and size. |
outcome, time |
Optional measurement columns. |
arm_observation_id |
Unique row ID column; defaults to row numbers. |
standardizer |
|
correction |
Apply the exact gamma-ratio Hedges correction using the denominator degrees of freedom. The resulting sampling covariance remains a delta-method approximation. |
correlations |
Named study matrices of individual-level correlations,
dimension names matching arm observation IDs. Required for repeated measurements
unless |
overlap |
Named study matrices of participant overlap counts. Required for correlated measurements with unequal sample sizes. With equal sizes and supplied correlations, omitted overlap means the same participants were measured. |
assume_independent |
Explicitly assume independence for different measurement rows when correlations are unavailable. |
all_contrasts |
Return every pair instead of baseline contrasts. Such rows can be redundant; the estimator rejects singular sampling covariance. |
Value
A list with data, named sampling_covariance study blocks, and
metadata. Use the returned observation_id column when fitting.
Examples
arms <- data.frame(study = 1, treatment = c("A", "B", "C"),
m = c(10, 12, 13), s = c(3, 4, 3), n = c(25, 30, 28))
network_smd_data(arms, "study", "treatment", "m", "s", "n",
assume_independent = TRUE)
Plot network treatment effects over numeric follow-up times
Description
Plot network treatment effects over numeric follow-up times
Usage
network_trajectory_plot(
object,
time,
comparator = object$reference,
treatments = setdiff(object$treatments, comparator),
newdata = NULL,
ci_level = 0.95,
prediction = FALSE,
benefit_direction = NULL,
main = "Treatment effects over time",
point_cex = 1,
label_cex = 1
)
Arguments
object |
A one-stage coherent fit with time-specific means or a numeric time moderator. |
time |
Name of the numeric time column. |
comparator |
Treatment used as comparator. |
treatments |
Treatments to display; defaults to all other treatments. |
newdata |
Optional prediction rows containing time and all other strata and moderators. Required for fixed time trends and multiple outcomes. |
ci_level |
Confidence level. |
prediction |
Include dashed new-study prediction bounds. |
benefit_direction |
Optional |
main |
Plot title. |
point_cex |
Scaling for point markers. |
label_cex |
Scaling for treatment/axis labels. Font family and style
inherit base graphics settings such as |
Value
Invisibly returns prediction rows, including interval bounds.
Examples
dat <- data.frame(study = 1:6, a = rep(c("A", "A", "B"), 2),
b = rep(c("B", "C", "C"), 2),
yi = c(.2, .5, .3, .3, .6, .4), vi = .04)
repeated <- rbind(transform(dat, time = 0),
transform(dat, study = study + 6, time = 6, yi = yi + .1))
fit <- network_meta(repeated, "study", "a", "b", "yi", "vi",
time = "time", treatment_effects = "by_time")
network_trajectory_plot(fit, time = "time")
Summarize effect modifiers across network comparisons
Description
Describe numeric and categorical effect modifiers to support substantive assessment of transitivity. This function does not test transitivity.
Usage
network_transitivity(data, study_id, treatment_1, treatment_2, modifiers)
Arguments
data |
Contrast data containing study IDs, treatment labels and modifiers. |
study_id, treatment_1, treatment_2 |
Study and treatment column names. |
modifiers |
Numeric or categorical modifier column names. Encode numeric category codes as factors if categorical summaries are intended. |
Details
Treatment pairs are labelled without regard to contrast direction. For each modifier separately, identical study/comparison/value combinations are counted once. Different values within the same study and comparison remain distinct. The function summarizes supplied comparison rows; it does not reconstruct unreported or implied multi-arm comparisons.
For numeric modifiers, retain finite values and calculate the arithmetic mean,
sample SD and range. observed counts finite deduplicated values; studies counts
unique studies in that comparison, including those without a finite modifier.
Means/ranges are missing if no finite values remain; SD is missing with fewer
than two values. These are observation summaries, not sample-size-weighted means.
For nonnumeric modifiers, each observed category has a row. Missing values form
an additional category labelled NA. observed is its count and proportion
is that count divided by all deduplicated values, including missing values.
Categories absent from a comparison are not added as zero-count rows. When a
study has different values, proportions need not equal proportions of studies.
Compare distributions across treatment comparisons with clinical knowledge of which variables modify relative effects. Differences in age, severity, follow-up, intervention definitions or risk of bias can motivate further investigation or prespecified meta-regression. Similar summaries cannot exclude unmeasured effect modification; differing summaries alone do not demonstrate statistical incoherence. Large amounts of missing modifier information weaken the assessment.
Value
A data frame containing comparison, modifier, type, category,
studies, observed, mean, sd, min, max, and proportion.
Numeric rows have missing category/proportion; categorical rows have missing
numeric summary fields. studies is repeated across category rows.
See Also
network_incoherence(), network_nodesplit().
Examples
d <- data.frame(study=1:4,a="A",b=c("B","B","C","C"),
age=c(30,40,50,60),risk=c("low","high","low",NA))
network_transitivity(d,"study","a","b",c("age","risk"))
Olkin & Siotani variance-covariance matrix
Description
Computes the Olkin & Siotani (1976) asymptotic variance-covariance matrix for the unique elements of one or more correlation matrices. The resulting matrices can be used as within-study sampling covariance matrices when synthesizing dependent correlations.
Usage
olkin_siotani(data, n, type = c("average", "weighted", "simple"))
Arguments
data |
A list of square, symmetric correlation matrices. Each matrix
should contain the same variables in the same order. Missing correlations
may be coded as |
n |
Numeric vector of study sample sizes, in the same order as |
type |
Character string specifying how the Olkin and Siotani numerator is computed before division by the study-specific sample sizes. See Details. |
Details
For a correlation matrix with p variables, each returned matrix has
p * (p - 1) / 2 rows and columns, corresponding to the vector of unique
off-diagonal correlations ordered as the pairs returned by
utils::combn(p, 2): (1, 2), (1, 3), ..., (p - 1, p). The function
returns one variance-covariance matrix per study.
Let R be the correlation matrix used for the numerator, and let r_ab
denote the correlation between variables a and b. For two correlations
indexed by variable pairs (s, t) and (u, v), the Olkin-Siotani numerator
element is
A_{st,uv} =
\frac{1}{2} r_{st} r_{uv}
\left(r_{su}^2 + r_{sv}^2 + r_{tu}^2 + r_{tv}^2\right)
+ r_{su} r_{tv} + r_{sv} r_{tu}
- r_{st} r_{su} r_{sv}
- r_{ts} r_{tu} r_{tv}
- r_{us} r_{ut} r_{uv}
- r_{vs} r_{vt} r_{vu}.
For study i, the returned sampling variance-covariance matrix is
A_i/n_i, where A_i is either study-specific or computed from a pooled
correlation matrix depending on type.
The type argument controls how the correlation matrix used in the
Olkin-Siotani numerator is obtained:
-
average: Averages the correlation matrices element-wise using all available data, computes a single Olkin-Siotani numerator from that average matrix, and divides copies of that numerator by each study's sample size. -
weighted: Forms a sample-size-weighted average correlation matrix. For each correlation, studies withNAdo not contribute to the weighted denominator. A single Olkin-Siotani numerator is computed from the weighted average matrix and divided by each study's sample size. -
simple: Computes the Olkin-Siotani numerator separately for each study's correlation matrix after replacing missing correlations with zero, then divides each numerator by that study's sample size.
The average and weighted options impose a common correlation structure
across studies for the numerator, while simple lets the within-study
covariance structure vary by study.
Value
A list of variance-covariance matrices with the same length as
data. Each matrix corresponds to one study and is scaled by the
associated value in n.
References
Becker, B. J. (1992). Using results from replicated studies to estimate linear models. Journal of Educational Statistics, 17(4), 341-362.
Olkin, I. and Siotani, M. (1976). Asymptotic distribution of functions of a correlation matrix. In S. Ikeda, T. Hayakawa, P. K. Sen, M. Siotani, and Y. Fujikoshi (Eds.), Essays in Probability and Statistics: A Volume in Honor of Professor Junjiro Ogawa (pp. 235-251). Shinko Tsusho.
Examples
R1 <- matrix(c(1, .30, .20,
.30, 1, .40,
.20, .40, 1), 3, 3)
R2 <- matrix(c(1, .25, .10,
.25, 1, .35,
.10, .35, 1), 3, 3)
olkin_siotani(list(R1, R2), n = c(80, 100), type = "simple")
Derived Effects from a Synthesized Path Model
Description
Compute products of directed coefficients, such as indirect effects, using the joint coefficient covariance across regression equations.
Usage
path_effects(object, paths, level = 0.95)
Arguments
object |
A fitted |
paths |
Named list of character vectors of directed edges, for example
|
level |
Confidence level, strictly between zero and one. |
Details
The gradient of each product is multiplied by the full joint directed-coefficient covariance. This retains uncertainty across equations. Wald intervals are approximations, especially for products near zero; no causal interpretation follows from pooled associations alone. If matched uncertainty is unavailable, estimates are returned with NA inference.
Value
A data frame of estimates, delta-method standard errors, pointwise
normal confidence intervals and p-values, with a vcov attribute.
Examples
d <- data.frame(ID=1:5,N=200,m_x=.2,y_x=.3,y_m=.4)
synthesis <- mars(d,studyID="ID",effectID="numID",sample_size="N",
effectsize_type="cor",variable_names=c("m_x","y_x","y_m"),
varcov_type="weighted",estimation_method="FE")
fit <- path_model(synthesis,"m ~ x\ny ~ x+m")
path_effects(fit,list(indirect=c("x -> m","m -> y"),direct="x -> y"))
Path Model Function
Description
Fit path or latent-variable models to a synthesized correlation matrix and optionally propagate uncertainty from the meta-analytic synthesis into the path coefficients.
Usage
path_model(
mars_object,
model,
num_obs = NULL,
adjust_se = TRUE,
se_method = c("delta", "simulation", "bootstrap"),
vcov_source = c("model", "robust"),
se_draws = 1000,
se_seed = NULL,
method_null = "sem",
synthesis_method = c("model", "average", "weighted"),
synthesis_transform = c("none", "fisher_z"),
missing_corr = c("available", "pairwise", "em"),
attenuation = c("none", "correct"),
reliability = NULL,
reliability_missing = c("error", "skip", "impute_mean", "assume_1"),
pd_adjust = c("none", "eigen_clip", "nearpd"),
pd_tol = 1e-08,
fit_method = c("auto", "wls", "descriptive"),
...
)
Arguments
mars_object |
The mars fitted object, or an object returned by
|
model |
Model syntax in a lavaan-like format. Regression paths use
|
num_obs |
Optional size used only by internal descriptive calculations. It does not calibrate fit tests for synthesized correlations. WLS uses the supplied sampling covariance and does not use this argument. |
adjust_se |
Logical; if |
se_method |
|
vcov_source |
Source of pooled-correlation uncertainty. |
se_draws |
Number of draws/resamples used when
|
se_seed |
Optional random seed for |
method_null |
Null-model method for observed-variable path models.
Currently |
synthesis_method |
Correlation synthesis method used to build the
matrix supplied to latent/path modeling. One of |
synthesis_transform |
Optional transform applied for
|
missing_corr |
Missing-correlation handling for synthesized matrices.
One of |
attenuation |
Attenuation-correction mode for synthesized correlations.
One of |
reliability |
Reliability input used when |
reliability_missing |
Strategy for missing reliability values.
One of |
pd_adjust |
Positive-definite repair applied to the synthesized
correlation matrix prior to model fitting. One of |
pd_tol |
Minimum eigenvalue tolerance used by
|
fit_method |
|
... |
Reserved for future extensions. |
Details
The synthesized correlation vector is ordered by the column-major lower
triangle. The model and its sampling covariance must describe the same
estimator and variable pairs. Model pooling uses fitted means; average and
sample-size-weighted pooling reconstruct correlations from study data.
Alternative pooling, attenuation correction or positive-definite repair has
no matched sampling covariance in this workflow, so auto fitting is descriptive
and corresponding uncertainty is withheld. Repair magnitude and eigenvalues
are recorded in synthesis.
WLS minimizes
Q(\theta)=(\hat r-r(\theta))^T V_{\hat r}^{-1}(\hat r-r(\theta)).
RAM matrices define the model-implied covariance. Observed residual variances are computed to constrain all observed variances to one. Latent factors use a marker loading of one unless a nonzero loading or positive factor variance is fixed explicitly. Numeric fixed loadings and residual covariances are supported; fixed endogenous variances, mean structures and equality labels are not supported by this WLS interface. Variance bounds, covariance validity, optimization convergence and local Jacobian rank are checked. All specified paths are fit jointly; overidentified WLS coefficients need not equal coefficients from separate regressions on the pooled matrix.
For q correlations and Jacobian rank d, the asymptotic global test is
chi-square with q-d degrees of freedom, conditional on the estimated
sampling covariance. A saturated model has zero degrees of freedom and no
global p-value. CFI and TLI use an independence model with the same weights;
raw and bounded indices are returned. RMSEA is unavailable because a single
effective sample size is not specified for synthesized correlations. SRMR is
descriptive. Small numbers of studies, estimated heterogeneity and estimated
robust covariances limit the asymptotic calibration.
WLS parameter covariance is the inverse expected information
(J^T V_{\hat r}^{-1}J)^{-1}, without a residual-scale multiplier.
This can differ from observed-Hessian standard errors. All directed paths
retain their joint covariance in computed_vcov; path_effects() uses it for
direct and indirect effects across equations. CFA also reports raw and
standardized loadings and marginal factor correlations. Fixed paths receive
no coefficient p-values. Normal Wald inference is pointwise and unadjusted.
Descriptive observed-variable models compute standardized regression
coefficients from their correlation submatrices. Descriptive latent models
minimize a normal-theory covariance discrepancy, with log-scale variances.
Their chi-square, CFI, TLI and RMSEA are withheld for synthesized data even
when num_obs is provided. Supplying a sample size does not replace the
sampling covariance required for synthesis-aware inference.
Simulation and bootstrap fits use the same fitting objective as the point estimate. Invalid correlations and inadmissible fits are counted, not silently repaired. The reported uncertainty conditions on accepted draws and on the chosen synthesis/model specification; inspect acceptance rates and perform sensitivity analyses when exclusions are substantial.
Value
List output with class path; The output is the parameter estimates from the fitted path model, joint directed-coefficient covariance, fitting method, uncertainty diagnostics and standardized factor details.
Examples
fit <- mars(
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"
)
)
path_model(fit, "Performance ~ Cognitive + Somatic + Selfconfidence")
Permutation mars wrapper
Description
This is a wrapper around mars() to perform one permutation replicate.
Independent univariate mean models permute effect signs. Global moderator
tests permute entire moderator blocks relative to effects and sampling variances.
Dependent, scale, LASSO, and supplied-weight models are rejected.
Usage
permutation_mars(
data,
studyID,
effectID = NULL,
sample_size = NULL,
effectsize_type = NULL,
formula = NULL,
variable_names = NULL,
effectsize_name = NULL,
estimation_method = NULL,
variance = NULL,
varcov_type = NULL,
weights = NULL,
structure = NULL,
intercept = FALSE,
missing = "remove",
optim_method = "L-BFGS-B",
robustID = NULL,
multivariate_covs = NULL,
lasso = FALSE,
lasso_args = list(),
tol = NULL,
scheme = c("auto", "sign", "moderators"),
assume_exchangeable = FALSE,
...
)
Arguments
data |
Data used for analysis |
studyID |
Character string representing the study ID |
effectID |
Character string representing the effect size ID |
sample_size |
Character string representing the sample size of the studies. |
effectsize_type |
Type of effect size being analyzed |
formula |
The formula used for specifying the fixed and random structure. |
variable_names |
Vector of character strings representing the attributes with correlations. The attributes that are correlated should be separated by an underscore. |
effectsize_name |
Character string representing the name of the effect size column in the data. |
estimation_method |
MLE or REML; NULL uses REML. |
variance |
Character string representing the name of the variance of the effect size in the data. |
varcov_type |
Type of variance covariance matrix computed. |
weights |
User specified matrix of weights for analysis. |
structure |
Between-study covariance structure; NULL infers it from formula. |
intercept |
Whether a model intercept should be specified. |
missing |
Whether missing data should be removed, or kept. |
optim_method |
Optimization method that is passed to the optim function. |
robustID |
A character vector specifying the cluster group to use for computing the robust standard errors. |
multivariate_covs |
A one-sided formula to specify the covariates used in a multivariate analysis. |
lasso |
Must be FALSE; LASSO permutation inference is unsupported. |
lasso_args |
Named controls for mars_lasso(), such as folds and selection. |
tol |
NULL retains the fitting engine's default tolerance. |
scheme |
auto selects sign changes for intercept-only models and moderator permutation otherwise. sign requires independent symmetric errors around zero. |
assume_exchangeable |
Set TRUE only when moderator blocks are exchangeable relative to effects and variances under the global null of all slopes zero. |
... |
Additional arguments forwarded to mars(), such as tau2 or robust_args. |
Details
This function returns one transformed fit. Use replicate_permutation() for inference, which retains the observed model and null statistics.
Examples
perm_fit <- permutation_mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
Plot alternative-estimation replications
Description
Visualize replicate estimates from bootstrap, jackknife, or permutation output on a single base R figure.
Usage
## S3 method for class 'mars_boot'
plot(
x,
terms = NULL,
xlab = "Estimate",
ylab = "Frequency",
main = NULL,
breaks = "Sturges",
col = "grey85",
border = "white",
panel_layout = NULL,
...
)
Arguments
x |
A |
terms |
Optional character vector of terms to plot. Defaults to the fixed effect terms stored in the model summary when available, otherwise all replicated terms. |
xlab |
Label for the x-axis. |
ylab |
Label for the y-axis. |
main |
Optional plot title. If |
breaks |
Histogram breaks passed to |
col |
Fill color for the histograms. |
border |
Border color for the histograms. |
panel_layout |
Optional length-2 numeric vector giving the
|
... |
Additional arguments passed to the underlying base plotting call. |
Value
Invisibly returns the matrix of replicated estimates that was plotted.
Examples
boot_reps <- replicate_bootstrap(
number_bootstraps = 5,
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
boot_stats <- compute_alt_stats(boot_reps)
plot(boot_stats, terms = "(Intercept)")
Plot Profile-Likelihood Curves
Description
Draw a one-dimensional profile-likelihood curve or a two-dimensional profile-likelihood surface.
Usage
## S3 method for class 'profile_likelihood'
plot(
x,
parameter = NULL,
type = c("profile", "contour", "image"),
line_col = "#C0392B",
line_lwd = 2,
cutoff_col = "#7F8C8D",
mle_col = "#1F618D",
point_col = "#C0392B",
surface_cols = grDevices::hcl.colors(12, "YlOrRd", rev = TRUE),
xlab = NULL,
ylab = "Objective",
main = NULL,
...
)
Arguments
x |
An object returned by |
parameter |
Optional parameter name to plot. Defaults to the first available profile. |
type |
Plot type. Use |
line_col |
Line color for the profile curve. |
line_lwd |
Line width for the profile curve. |
cutoff_col |
Color used for the profile-likelihood cutoff line. |
mle_col |
Color used for the MLE reference line. |
point_col |
Color used for profiled grid points. |
surface_cols |
Colors used for two-dimensional image plots. |
xlab |
Optional x-axis label. |
ylab |
Optional y-axis label. |
main |
Plot title. When |
... |
Additional graphical arguments passed to |
Details
For type = "profile", the x-axis is the fixed parameter value and the
y-axis is the deviance-scale objective after re-optimizing all remaining
parameters. The vertical reference line marks the fitted value and the
horizontal reference line marks the profile-likelihood cutoff.
For type = "contour" or type = "image", the x- and y-axes are the two
fixed parameter values and the contours show the same deviance-scale
objective after re-optimizing all remaining parameters. The emphasized
contour marks the approximate joint confidence-region cutoff for the pair.
Value
Invisibly returns the plotted profile data frame.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
prof <- profile_random_effects(fit, n_points = 5)
plot(prof)
Plot residual diagnostics panels for MARS models
Description
Draw a compact three-panel residual diagnostic figure showing raw residuals versus fitted values, a studentized residual QQ plot, and a studentized residual histogram.
Usage
plot_residual_panel(
fit,
main_prefix = "Model",
fitted_jitter = 0,
hist_breaks = "auto",
hist_rug = TRUE,
...
)
Arguments
fit |
A fitted |
main_prefix |
Prefix used for the panel titles. |
fitted_jitter |
Non-negative numeric scalar giving the horizontal jitter
amount applied to fitted values in the raw-residual-versus-fitted panel.
Use |
hist_breaks |
Histogram breaks for the studentized residual panel. Use
|
hist_rug |
Logical; if |
... |
Additional arguments passed to the first |
Value
Invisibly returns a data frame containing the fitted values, jittered fitted values used for plotting, raw residuals, studentized residuals, and the histogram break rule used.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
plot_residual_panel(fit)
Summarize, predict, and plot diagnostic accuracy
Description
Summarize, predict, and plot diagnostic accuracy
Usage
## S3 method for class 'mars_dta'
predict(
object,
newdata = NULL,
level = 0.95,
interval = c("confidence", "prediction"),
...
)
## S3 method for class 'mars_dta'
coef(object, ...)
## S3 method for class 'mars_dta'
vcov(object, ...)
## S3 method for class 'mars_dta'
summary(object, newdata = NULL, level = 0.95, ...)
## S3 method for class 'mars_dta'
print(x, ...)
## S3 method for class 'summary.mars_dta'
print(x, ...)
## S3 method for class 'mars_dta'
plot(
x,
newdata = NULL,
level = 0.95,
...,
xlim = c(0, 1),
ylim = c(0, 1),
xlab = "False-positive rate",
ylab = "Sensitivity",
sroc = FALSE
)
Arguments
object, x |
A fitted |
newdata |
Data frame with one row per moderator profile. Required for prediction and plotting when the fit has moderators. A summary without profiles reports the fitted coefficients. |
level |
Confidence or prediction level between zero and one. |
interval |
Use |
... |
For |
xlim, ylim, xlab, ylab |
Axis limits and labels for the ROC plot. |
sroc |
Logical. Overlay the |
Details
The reported operating point is the inverse logit of the fitted mean for each endpoint. Intervals are Wald intervals computed on the logit scale and back-transformed. Prediction intervals add the estimated between-study variance and describe true study accuracy. The plot takes one moderator profile and shows raw study estimates with joint confidence and prediction regions formed on the logit scale and transformed onto ROC axes. For binomial fits, the coefficient covariance comes from the observed information of the integrated likelihood. If that information cannot be inverted, interval limits are missing and the ROC plot omits the regions.
Value
predict() returns a data frame with two rows per profile.
summary() returns study counts, coefficients, pooled accuracy when
profiles are available, and heterogeneity and convergence diagnostics.
plot() invisibly returns the summary point and region coordinates,
plus the curve coordinates when sroc = TRUE.
coef() and vcov() return the logit-scale coefficients and their
estimated covariance matrix.
Predict from a Random Forest Meta-Analysis
Description
Predict from a Random Forest Meta-Analysis
Usage
## S3 method for class 'mars_rf'
predict(
object,
newdata = NULL,
type = c("response", "working", "matrix"),
re_form = c("conditional", "population"),
matrix_action = c("warn", "error", "repair", "none"),
...
)
Arguments
object |
Fitted mars_rf object. |
newdata |
Data frame of raw predictors. NULL uses the prepared training data. Correlation matrix prediction additionally needs the internal effect and study ID columns named in object$effect_id and object$study_id. |
type |
response returns predictions on the effect scale; working returns the forest fitting scale; matrix returns complete named correlation matrices. |
re_form |
conditional includes available known-group BLUPs; population omits every random-effect contribution. Unknown groups receive zero BLUPs. |
matrix_action |
warn checks complete correlation matrices and reports invalid predictions; error rejects them; none skips checks; repair explicitly projects complete matrices using Matrix::nearPD(corr=TRUE). |
... |
Additional arguments are rejected. |
Details
Back-transforming Fisher-z predictions ensures pairwise bounds but does not ensure joint matrix validity. Raw-scale extrapolation can violate bounds. Repair requires each group to contain every effect ID exactly once; checks on vector predictions inspect only complete groups. Transformations and EM conditional moments are frozen at training. These are point predictions, without prediction intervals or confirmatory inference.
Value
A numeric vector or a list of correlation matrices. Matrix results include a diagnostics attribute with eigenvalues, repair indicators and maximum changes. Repaired vector results include matrix_diagnostics.
Predict treatment contrasts from a fitted network_meta model
Description
Predict treatment contrasts from a fitted network_meta model
Usage
## S3 method for class 'nma_mars'
predict(
object,
newdata,
se.fit = FALSE,
interval = c("none", "confidence", "prediction"),
level = 0.95,
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
...
)
Arguments
object |
A fitted |
newdata |
Data frame containing |
se.fit |
Logical; if TRUE, returns an approximate prediction standard error. |
interval |
Type of interval; one of |
level |
Confidence level for intervals. |
treatment_1, treatment_2 |
Column names used in |
... |
Unused. |
Value
Data frame with predicted contrast estimates and optional uncertainty.
Examples
nma_dat <- data.frame(
study = c("S1", "S2", "S3", "S4"),
treatment_1 = c("A", "A", "B", "A"),
treatment_2 = c("B", "C", "C", "B"),
effect = c(0.20, 0.35, 0.10, 0.15),
variance = c(0.04, 0.05, 0.04, 0.06)
)
nma_fit <- network_meta(
nma_dat,
study_id = "study",
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
effect = "effect",
variance = "variance",
model_type = "wls"
)
predict(
nma_fit,
data.frame(treatment_1 = "A", treatment_2 = "C"),
interval = "confidence"
)
Print a fitted path model
Description
Print a fitted path model
Usage
## S3 method for class 'mars_path'
print(x, fit_measures = TRUE, ...)
Arguments
x |
A fitted path model returned by |
fit_measures |
Logical; include model-fit statistics in the printed summary. |
... |
Additional arguments passed to the summary printer. |
Value
x, invisibly.
Within-design network heterogeneity
Description
Intended question: how much do study effects vary within the same treatment design, after allowing each design its own treatment means?
Usage
## S3 method for class 'nma_heterogeneity'
print(
x,
...,
digits = getOption("digits"),
estimable_only = TRUE,
detailed = FALSE
)
## S3 method for class 'nma_heterogeneity'
summary(
object,
...,
digits = getOption("digits"),
estimable_only = TRUE,
detailed = FALSE
)
network_heterogeneity(object)
Arguments
x |
A result from |
... |
Additional arguments forwarded to |
digits |
Decimal places, an integer from 1 to 22; defaults to
|
estimable_only |
Logical; show only designs with positive independently
testable residual df (default |
detailed |
Logical; show all diagnostic columns and additional returned
components (default |
object |
A fitted coherent network model; for |
Details
The printout follows its research question with the null hypothesis of no residual within-design heterogeneity beyond sampling variation. The overall Q test applies across designs; each testable design row applies the same null within that design. I-squared is descriptive, with no separate test.
A design is the set of treatments observed in a study. Fit the augmented
design-by-treatment mean by GLS using sampling covariance alone, preserving
shared-arm dependence. The residual Q is within-design heterogeneity; between-
design disagreement is excluded from this Q. This is the within-design part
of network_q_decomposition(), not a sum of local incoherence tests.
Design-specific contributions use residual quadratic forms in each design. With independent design mean spaces their residual df and chi-squared p-values are reported. If mean parameters, such as moderator slopes, are shared across designs, the Q contributions remain additive but design-specific df and p-values are missing, with a reason. The overall residual test remains valid under its usual Gaussian known-sampling-covariance assumptions.
Overall and design-specific I2_percent use the Q-based descriptive measure
100\max(0,1-df/Q). For positive independently testable df, Q less than
or equal to df (including zero) gives zero. Zero or unavailable df gives
NA, including design-specific df unavailable because moderator slopes are
shared. I-squared describes excess residual variation relative to sampling
variation after allowing design-specific means. It is not a fitted variance
component, a direct/indirect incoherence measure, or an additive partition:
design-specific I-squared values cannot be summed or averaged to obtain the
overall within-design I-squared. Small numbers of studies limit its precision.
Q uses no fitted random-effect covariance, even for a random-effects input.
fitted_heterogeneity separately reports the input model's variance summaries;
it is not a new estimate under the design-specific mean model. For uncertainty
in one common variance use network_heterogeneity_profile(). Heterogeneity and
incoherence are distinct; small within-design Q p-values do not establish
direct/indirect disagreement, and large values do not establish homogeneity.
Value
A list with overall (within-design Q, df, p-value and I2_percent),
by_design (design, study/contrast counts, Q, residual df, p-value,
I2_percent and reason),
decomposition (total/within/between Q), fitted_heterogeneity (the input
model's heterogeneity summary), question and assumption, with class
nma_heterogeneity. Default printing shows overall Q and only independently
testable designs, under the heading Within-design Q, using design, Q, df,
p-value and I2 (%) columns. Print/summary
accept digits, estimable_only, and detailed; filtering changes only
the display. Shared moderator slopes can preclude independent design tests.
Zero residual df
has a missing p-value. Q contributions are additive; their p-values are not.
References
Krahn, U., Binder, H., and König, J. (2013). A graphical tool for locating inconsistency in network meta-analyses. BMC Medical Research Methodology, 13, 35. doi:10.1186/1471-2288-13-35.
See Also
network_q_decomposition(), network_heterogeneity_profile(),
network_incoherence(), network_design_incoherence()
Examples
d <- data.frame(s=1:9,a=rep(c("A","A","B"),3),
b=rep(c("B","C","C"),3),g=rep(c(.2,.6,.2),3),v=.04)
f <- network_meta(d,"s","a","b","g","v")
network_heterogeneity(f)
Decompose network residual Q into within-design and between-design variation
Description
Decompose network residual Q into within-design and between-design variation
Usage
## S3 method for class 'nma_q_decomposition'
print(x, ..., digits = getOption("digits"), row.names = FALSE)
## S3 method for class 'nma_q_decomposition'
summary(object, ..., digits = getOption("digits"))
network_q_decomposition(object)
Arguments
x |
A result from |
... |
Additional arguments forwarded to |
digits |
Decimal places to display, an integer from 1 to 22;
defaults to |
row.names |
Logical; print row names (default |
object |
A fitted coherent network model. |
Details
The printed question asks whether residual variation occurs within designs, between designs, or both. Each row has a distinct null hypothesis: total: study effects follow the coherent mean model with sampling variation only; within_designs: study effects follow the design-specific mean model with sampling variation only; between_designs: design-specific means are compatible with a coherent network. The printout states these hypotheses before the corresponding component statistics.
Uses the supplied sampling covariance alone, without adding fitted heterogeneity. The coherent mean model is nested inside a design-by-treatment mean model, retaining the original moderator slopes and mean strata. GLS residual sums of squares give total and within-design Q; their difference is between-design incoherence Q. Degrees of freedom use the corresponding mean ranks. For models with shared moderator slopes this is a conditional residual decomposition, rather than a sum of separately fitted design analyses. Existing local design-deviation tests are overlapping and are not additive.
Value
A three-row data frame with component, statistic, df, p_value,
and covariance, of class nma_q_decomposition. Printing omits the repeated
covariance column and states the sampling-only assumption once above the
results; the returned column is retained for programmatic use. Zero residual
df has a missing p-value.
References
Higgins, J. P. T., Jackson, D., Barrett, J. K., Lu, G., Ades, A. E., and White, I. R. (2012). Consistency and inconsistency in network meta-analysis: concepts and models for multi-arm studies. Research Synthesis Methods, 3, 98–110. doi:10.1002/jrsm.1044.
White, I. R., Barrett, J. K., Jackson, D., and Higgins, J. P. T. (2012). Consistency and inconsistency in network meta-analysis: model estimation using multivariate meta-regression. Research Synthesis Methods, 3, 111–125. doi:10.1002/jrsm.1045.
White, I. R. (2015). Network meta-analysis. The Stata Journal, 15(4), 951–985. Section 3.6, Table 1. doi:10.1177/1536867X1501500403.
Qin, L., Zhao, S., Guo, W., Tong, T., and Yang, K. (2024). A comparison of two models for detecting inconsistency in network meta-analysis. Research Synthesis Methods, 15(6), 851–871. doi:10.1002/jrsm.1734.
See Also
network_incoherence(), network_design_incoherence()
Examples
dat <- data.frame(study = 1:6, a = rep(c("A", "A", "B"), 2),
b = rep(c("B", "C", "C"), 2),
yi = c(.2, .5, .3, .3, .6, .4), vi = .04)
fit <- network_meta(dat, "study", "a", "b", "yi", "vi")
network_q_decomposition(fit)
PRISMA Flow Diagram (Base R)
Description
Draws a PRISMA-style flow diagram using base graphics, with support for both new reviews and updated reviews.
Usage
prisma_diagram(
counts,
review_type = c("new", "updated"),
labels = NULL,
show_exclusion_boxes = TRUE,
main = "PRISMA Flow Diagram",
box_fill = "white",
box_border = "black",
arrow_col = "black",
text_col = "black",
cex = 0.78,
cex_main = 1.05,
main_adj = 0.5,
main_line = NULL,
line_lwd = 1.3,
box_width = 0.36,
side_box_width = 0.23,
box_height = 0.085,
box_gap = 0.045,
side_gap = 0.05,
wrap_labels = TRUE,
font_family = "sans",
font_face = 1,
title_font_face = 2,
arrow_length = 0.055,
arrow_angle = 22
)
Arguments
counts |
Named counts used in the flow diagram. Accepted formats are:
|
review_type |
Type of review flow to draw: |
labels |
Optional named character vector/list to override default box labels. Names must correspond to known flow elements. |
show_exclusion_boxes |
Logical. If |
main |
Main plot title. |
box_fill |
Fill color for boxes. |
box_border |
Border color for boxes. |
arrow_col |
Arrow color. |
text_col |
Text color used inside boxes. |
cex |
Text size for box labels. |
cex_main |
Title size. |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
line_lwd |
Line width for box borders and arrows. |
box_width |
Width of central flow boxes. |
side_box_width |
Width of side boxes. |
box_height |
Box height. |
box_gap |
Vertical gap between central flow boxes. |
side_gap |
Horizontal gap between central and side boxes. |
wrap_labels |
Logical. If |
font_family |
Font family used for the diagram text. |
font_face |
Font face used for box text ( |
title_font_face |
Font face for the main title. |
arrow_length |
Arrowhead length. |
arrow_angle |
Arrowhead angle in degrees. |
Details
The function is intentionally flexible: counts can be a named numeric
vector, named list, or one-row data frame.
Value
Invisibly returns a list containing:
- counts
Named numeric counts used for plotting (including computed totals for updated reviews).
- labels
Named character vector of labels used in the boxes.
- review_type
Review type used (
"new"or"updated").
Examples
new_counts <- c(
records_identified = 1240,
records_removed = 210,
records_screened = 1030,
records_excluded = 860,
reports_sought = 170,
reports_not_retrieved = 14,
reports_assessed = 156,
reports_excluded = 120,
studies_included = 36
)
prisma_diagram(new_counts)
updated_counts <- c(
records_identified = 420,
records_removed = 60,
records_screened = 360,
records_excluded = 290,
reports_sought = 70,
reports_not_retrieved = 6,
reports_assessed = 64,
reports_excluded = 50,
studies_included = 14,
previous_reports = 80,
previous_studies = 22
)
prisma_diagram(updated_counts, review_type = "updated")
Profile Likelihood for mars Models
Description
Compute one-dimensional profile-likelihood curves and confidence intervals for selected parameters by fixing one parameter at a time and re-optimizing the remaining parameters.
Usage
profile_likelihood(
object,
parameters = NULL,
level = 0.95,
n_points = 21,
span = 3,
grid = NULL,
optim_method = "L-BFGS-B",
control = list(factr = 1e+07, maxit = 400),
parameter_pairs = NULL
)
Arguments
object |
A fitted |
parameters |
Optional parameter specification. May be |
level |
Confidence level for profile-likelihood intervals. Default |
n_points |
Number of grid points used per profiled parameter. Default |
span |
Automatic grid width. For coefficients, the grid extends this
many selected coefficient SEs on each side; positive nuisance parameters
use a multiplicative span. Default |
grid |
Optional custom grid specification:
|
optim_method |
Optimization method passed to |
control |
Control list passed to |
parameter_pairs |
Optional 2D parameter-pair specification. May be a character vector of length 2, a numeric vector of length 2, or a list of such pairs. |
Details
The profiled objective is reported on a deviance-like scale. For standard
mars models this is the fitted objective, equivalent to -2 log L up to
constants that do not depend on the profiled parameters. For publication-bias
models the same -2 log L scaling is used. Lower values therefore indicate
better-supported parameter values.
For a one-dimensional profile, the x-axis is the fixed value of the selected
parameter and the y-axis is the deviance-scale objective after all remaining
parameters have been re-optimized. The profile-likelihood interval contains
values whose objective is no more than qchisq(level, df = 1) above the
fitted minimum.
For a two-dimensional profile surface, the x- and y-axes are the two fixed
parameter values and the contours show the deviance-scale objective after all
other parameters have been re-optimized. The cutoff contour uses
qchisq(level, df = 2) above the fitted minimum and can be interpreted as an
approximate joint confidence region for the parameter pair.
The profiling likelihood is checked against the original fitted objective. Stored outcome indices preserve missing outcomes and reordered study rows. Failed conditional fits are flagged and excluded from interval interpolation; a profile with no converged finite evaluations raises an error. Expand the grid when an interval endpoint is not bracketed. Wald chi-square cutoffs are approximate; variance boundaries require special interpretation. Coefficient profiles require ML; REML is supported only for heterogeneity profiles.
Value
A list containing per-parameter profile grids and profile-likelihood
confidence intervals. The profiles component contains one data frame per
one-dimensional profile. The surfaces component contains optional
two-dimensional grids with x, y, objective, converged, and cutoff
entries.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
prof <- profile_likelihood(fit, parameters = "tau1", n_points = 7)
plot(prof)
Profile Likelihood for Random-Effects Variance Parameters
Description
Compute profile-likelihood curves and confidence intervals for random-effects heterogeneity optimizer parameters by fixing one parameter at a time and re-optimizing all remaining parameters.
Usage
profile_random_effects(
model,
tau_indices = NULL,
level = 0.95,
n_points = 21,
span = 3,
grid = NULL,
optim_method = "L-BFGS-B",
control = list(factr = 1e+07, maxit = 400)
)
Arguments
model |
A fitted |
tau_indices |
Optional indices (1-based) of random-effects parameters to profile. Defaults to all random-effects parameters. |
level |
Confidence level for profile-likelihood intervals. Default |
n_points |
Number of grid points used per profiled parameter. Default |
span |
Multiplicative span around the MLE for automatic grids. Default |
grid |
Optional custom grid specification:
|
optim_method |
Optimization method passed to |
control |
Control list passed to |
Value
A list containing per-parameter profile grids and profile-likelihood CIs.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
profile_random_effects(fit, n_points = 7)
Publication-Bias Selection Models and Small-Study Diagnostics
Description
Fits a normal selection likelihood to an ordinary fitted mars() model.
Estimates describe sensitivity to a specified selection mechanism. A changed
estimate or significant asymmetry test does not establish publication bias.
Usage
publication_bias(
mars_object,
method = c("beta_selection", "beta_binomial", "logistic_selection"),
p_value_tail = c("two.sided", "right", "left"),
n_bins = 10,
p_value_min = NULL,
maxit = 2000,
integration_control = list(),
starts = 3L,
gradient_tol = 1e-04,
level = 0.95,
funnel_plot = FALSE,
funnel_args = list(),
control = list(),
comparison_vcov = c("model", "robust"),
inference = c("model", "sandwich"),
egger_robust_args = list(type = "CR1S", inference = "naive-t"),
...
)
Arguments
mars_object |
Ordinary fitted mars object. Penalized fits are unsupported. |
method |
beta_selection, beta_binomial or logistic_selection; see Details for their exact weight functions. The names do not imply equivalence to similarly named models in other software. |
p_value_tail |
With |
n_bins |
Integer at least three. Beta-binomial bins are |
p_value_min |
P-value censoring threshold: |
maxit |
Positive integer iteration limit for each optimization start. control$maxit overrides this value. |
integration_control |
Named list: rel_tol (default 1e-10) and subdivisions (1000) control scalar adaptive integration; bivariate_rel_tol (1e-9) and bivariate_subdivisions (500) control outer conditional-normal integration. Inner integrals use scalar settings. Tolerances are in (0,1); subdivision limits are positive integers. Beta-binomial scalar integrals use exact normal interval probabilities and do not depend on quadrature controls. Full infinite normal tails are retained. These settings are saved and reused by profiling. |
starts |
Integer from one to three. The default tries three deterministic initial selection shapes and heterogeneity values. One uses the parent means, parent positive tau2 (or 0.01 when zero), and shapes (1,1) for beta methods or (0,1) for logistic. Additional beta shapes are (0.5,2) and (2,0.5); logistic starts are (-2,0.5) and (2,2). Estimated initial tau2 is multiplied by 0.5 and 2 in those starts. Valid converged candidates take precedence; the smallest negative log likelihood among them is selected. If none converges, the best finite candidate is returned with unavailable Wald inference. |
gradient_tol |
Positive stationarity threshold, default 1e-4. The diagnostic is max(abs(gradient))/(1+abs(negative_log_likelihood)), where numerical study scores give the gradient on the optimizer scale. Failing it suppresses Wald inference even when optim reports convergence. It is sensitive to units and parameterization and does not prove a global optimum. |
level |
Confidence level in (0,1), default 0.95, for adjusted and unadjusted coefficient intervals in the comparison. Robust unadjusted intervals retain the parent's normal/t reference and coefficient-specific degrees of freedom. |
funnel_plot |
Logical; draw a funnel plot after fitting. |
funnel_args |
Uniquely named list of arguments passed to |
control |
Uniquely named BFGS controls: trace, REPORT, fnscale, parscale, ndeps, maxit, abstol and reltol. Positive fnscale retains minimization; parscale and ndeps must be positive vectors matching optimizer parameters. These control optimization, not quadrature. |
comparison_vcov |
model uses the parent model covariance and normal intervals; robust uses its stored cluster-robust covariance and reference distribution, requiring a parent fit with robustID. This does not change the selection-model fit or its inference setting. |
inference |
model uses the inverse observed Hessian; sandwich uses independent study score contributions. Nonconvergence, failed stationarity or invalid curvature produces unavailable SEs and Wald tests. |
egger_robust_args |
Named robust covariance controls for the separate
Egger-type test. Defaults to CR1S with a G-1 t reference. Other controls follow
|
... |
Unsupported arguments are rejected. |
Details
For study g, the selected density is
f_{sel}(y_g)=\phi(y_g;X_g\beta,V_g)
\prod_j w(p_{gj}) / E_{\phi}\{\prod_j w(p_{gj})\}.
Studies are independent. Within a study the product of outcome-specific weights defines the joint selection mechanism, while V_g retains dependence. This is not a general model of publication based on any one significant outcome, selective outcome omission or an unknown decision rule. Missing outcomes handled by the parent are not modeled as selective missingness. P-values test a zero effect using sampling SEs, without subtracting the fitted mean or including heterogeneity in the SE. Every reported and fitted p-value uses the same positive sampling variance, without a variance floor.
beta_selection uses w(p)=p^{\alpha-1}(1-p)^{\beta-1},
with \alpha,\beta>0.
Setting \alpha=\beta=1 gives constant selection. The shape may be nonmonotone.
beta_binomial uses the bin weights
w_j=\binom{m}{j}\frac{B(j+\alpha,m-j+\beta)}{B(\alpha,\beta)},
where m=n_{\mathrm{bins}}-1.
Setting \alpha=\beta=1 yields constant bin weights. These are relative
weights with a beta-binomial shape; their sum-one normalization does not make
them publication probabilities or observed p-value-bin probabilities.
logistic_selection uses w(p)=\operatorname{plogis}(a-b\log p),
with b>0. It is decreasing
in p; b approaching zero gives constant weights and can weaken identification
of a. This two-parameter function differs from metafor's model named logistic.
The beta kernel agrees with the Citkowicz–Vevea formulation when censoring,
tails, data and covariance assumptions match. Beta-binomial and logistic
functions here are specified sensitivity models, not interchangeable defaults.
Absolute weight scale cancels from the density. Relative displayed weights cannot identify the fraction of unpublished studies. Fitting uses log weights and normalizers. Independent covariance components factor exactly. Connected components of size two use deterministic conditional-normal integration; larger components are unsupported. Do not discard correlations to bypass this limit. Bivariate fitting can be expensive, particularly with three starts.
Univariate constant heterogeneity is re-estimated jointly by ML unless the parent fixed tau2. Fixed tau2, including zero, is preserved. Multivariate, multilevel and scale-location models condition on fitted parent covariance; scale coefficients and covariance parameters are not re-estimated. Their estimation uncertainty is omitted. Observation-local sampling matrices retain observation order; outcome-category indices select heterogeneity separately. Inconsistent covariance metadata are rejected. Inputs and numerical predictors should be expressed on a well-conditioned scale.
Means are unrestricted. Positive nuisance parameters are optimized on log scales. Estimated tau2 approaches zero but is not represented as an exact zero boundary. Multiple starts and a zero optim code do not guarantee a global maximum. Absolute log nuisance values exceeding 20 and estimated tau2 below 1e-8 are descriptive flags, not formal identifiability tests. Inspect curvature, start agreement, gradient, profiles and changes under tighter quadrature and alternative censoring thresholds; changed censoring fits are distinct models.
Model covariance is H^{-1} for the negative log likelihood. Sandwich covariance
is H^{-1}(\sum_g s_g s_g')H^{-1}, with no small-sample correction and more studies
than parameters required. Both require identifiable positive curvature and
use asymptotic normal Wald inference. Failure is reported as unavailable
inference, not a zero SE. No general finite-sample coverage is guaranteed.
Egger fits y/SE on an asymmetry intercept and the parent mean design divided by SE, without extra inverse-variance weighting. With a mean intercept only, this equals raw-effect regression on sampling SE with inverse-variance weights. Moderators are retained and inference uses the parent's stored robustID cluster when available, otherwise studyID. A rank-deficient design or invalid inference makes the check unavailable. Diagnostics flag fewer than ten studies and little SE variation. Ten studies is a rule of thumb, not a guarantee. Effect-SE coupling can create artefactual asymmetry, particularly for SMDs and odds ratios; assess suitability rather than automatically treating Egger as a bias test. Nonsignificance does not exclude missing evidence. See the Cochrane Handbook, Chapter 13.
Value
A pub_bias object. coefficients contains adjusted estimates, SEs, normal-reference z tests and p-values; adjusted_vs_unadjusted contains intervals, signed differences, percent change relative to abs(unadjusted), direction changes and interval overlap. Overlap is descriptive, not a test of the difference. selection contains shape parameters and estimated tau2 only when re-estimated. covariance_mode records covariance treatment; integration_control records quadrature settings. optimization_diagnostics stores each start's objective, convergence and selection, numerical gradient, stationarity, extreme nuisance parameters and near-zero estimated tau2. model_data stores aligned effects, sampling SEs, censored p-values, relative observed weights and mean predictions. egger_test is a separate diagnostic. summary() reports estimates, comparison, optimization and inference status.
References
Citkowicz, M., & Vevea, J. L. (2017). A parsimonious weight function for modeling publication bias. Psychological Methods, 22(1), 28-41. doi:10.1037/met0000119.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
bias_fit <- publication_bias(fit, method = "beta_selection")
summary(bias_fit)
Replicate the bootstrap computations
Description
Replicate the bootstrap computations
Usage
replicate_bootstrap(
number_bootstraps = 999,
future_seed = TRUE,
on_error = c("warn", "stop", "keep"),
...
)
Arguments
number_bootstraps |
The number of bootstraps to perform, default is 999. |
future_seed |
Seed control forwarded to |
on_error |
How failed replicate fits are handled: warn and retain, stop, or keep silently. The original full-data fit must succeed. |
... |
Additional function arguments to pass to the |
Details
Whole dependence blocks are sampled. Supplied weights must be positive definite, aligned with original rows, and independent between blocks. Supplied weights for expanded correlation data are unsupported. Fixed-effect factor levels, contrasts and transformed-predictor bases retain their original coordinates. Nonestimable original designs are recorded as failed fits.
Value
A list of replicate fits, with original_fit and robust_type attributes.
Examples
boot_reps <- replicate_bootstrap(
number_bootstraps = 5,
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
Replicate the jackknife computations
Description
Replicate the jackknife computations
Usage
replicate_jackknife(
data,
structure = NULL,
formula = NULL,
future_seed = TRUE,
on_error = c("warn", "stop", "keep"),
...
)
Arguments
data |
Data used for analysis. |
structure |
Between-study covariance structure; NULL infers it from formula. |
formula |
The formula used for specifying the fixed and random structure. |
future_seed |
Seed control forwarded to |
on_error |
How failed replicate fits are handled: warn and retain, stop, or keep silently. The original full-data fit must succeed. |
... |
Additional function arguments passed to |
Value
A named list of omission fits, with the full-data original_fit attribute.
Examples
jack_reps <- replicate_jackknife(
data = teacher_expectancy,
structure = "univariate",
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate"
)
Replicate network meta-analysis bootstraps
Description
Replicate network meta-analysis bootstraps
Usage
replicate_network_bootstrap(number_bootstraps = 999, future_seed = TRUE, ...)
Arguments
number_bootstraps |
Number of bootstrap replications. |
future_seed |
Seed control forwarded to
|
... |
Additional arguments passed to |
Value
A list of fitted "nma_mars" replicate objects.
Examples
nma_dat <- data.frame(
study = c("S1", "S2", "S3", "S4"),
treatment_1 = c("A", "A", "B", "A"),
treatment_2 = c("B", "C", "C", "B"),
effect = c(0.20, 0.35, 0.10, 0.15),
variance = c(0.04, 0.05, 0.04, 0.06)
)
boot_reps <- replicate_network_bootstrap(
number_bootstraps = 2,
data = nma_dat,
study_id = "study",
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
effect = "effect",
variance = "variance",
model_type = "wls"
)
Replicate network meta-analysis jackknife omissions
Description
Replicate network meta-analysis jackknife omissions
Usage
replicate_network_jackknife(data, study_id, future_seed = TRUE, ...)
Arguments
data |
A contrast-level network meta-analysis data frame. |
study_id |
Character string naming the study ID column. |
future_seed |
Seed control forwarded to
|
... |
Additional arguments passed to |
Value
A named list of fitted "nma_mars" replicate objects, named by
the omitted study.
Examples
nma_dat <- data.frame(
study = c("S1", "S2", "S3", "S4"),
treatment_1 = c("A", "A", "B", "A"),
treatment_2 = c("B", "C", "C", "B"),
effect = c(0.20, 0.35, 0.10, 0.15),
variance = c(0.04, 0.05, 0.04, 0.06)
)
jack_reps <- replicate_network_jackknife(
data = nma_dat,
study_id = "study",
treatment_1 = "treatment_1",
treatment_2 = "treatment_2",
effect = "effect",
variance = "variance",
model_type = "wls"
)
Replicate the permutation computations
Description
Replicate the permutation computations
Usage
replicate_permutation(
number_permutations = 999,
future_seed = TRUE,
exact = FALSE,
scheme = c("auto", "sign", "moderators"),
assume_exchangeable = FALSE,
alternative = c("two.sided", "greater", "less"),
max_exact = 50000L,
...
)
Arguments
number_permutations |
The number of permutations to perform, default is 999. |
future_seed |
Seed control forwarded to |
exact |
Enumerate every sign pattern or row permutation. Default FALSE. |
scheme |
auto selects sign changes for intercept-only models and moderator permutation otherwise. sign requires independent symmetric errors around zero. |
assume_exchangeable |
Set TRUE only when moderator blocks are exchangeable relative to effects and variances under the global null of all slopes zero. |
alternative |
Coefficient-test tail: two.sided, greater, or less. The global moderator Wald statistic always uses its upper tail. |
max_exact |
Maximum number of exact transformations, default 50000. |
... |
Additional function arguments passed to the |
Details
number_permutations counts random transformations; the observed fit is included once more to prevent zero p-values. Exact enumeration includes every transformation, including the identity. Any failed or non-estimable statistic withholds that test's p-value. Moderator p-values test the global null, not partial hypotheses conditional on nuisance moderators. Null-statistic quantiles are not confidence intervals. No permutation confidence intervals are supplied.
Value
A list with original_fit, robust_type, and permutation-statistic attributes.
Examples
perm_reps <- replicate_permutation(
number_permutations = 5,
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
Export Synthesis Reports
Description
Convenience exporters for synthesis_report objects. These helpers create
manuscript-ready report text in markdown, HTML, or DOCX format.
Usage
as_markdown(x, ...)
## S3 method for class 'synthesis_report'
as_markdown(x, file = NULL, digits = 3, ...)
as_html(x, ...)
## S3 method for class 'synthesis_report'
as_html(x, file = NULL, digits = 3, ...)
as_docx(x, ...)
## S3 method for class 'synthesis_report'
as_docx(x, file, digits = 3, ...)
Arguments
x |
A |
... |
Additional arguments reserved for future methods. |
file |
Output DOCX file path. This argument is required for Word export. |
digits |
Number of digits used in rendered numeric tables. |
Examples
fit <- mars(
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"
)
)
report <- synthesis_factor_report(fit, factor_method = "none")
markdown <- as_markdown(report)
html <- as_html(report)
as_docx(report, file = tempfile(fileext = ".docx"))
Residual Diagnostics for MARS Models
Description
Compute a compact residual-diagnostics summary that works across univariate,
multivariate, and multilevel mars fits.
Usage
residual_diagnostics(object, cluster = NULL, outcome = NULL)
Arguments
object |
A fitted |
cluster |
Optional column name in |
outcome |
Optional column name in |
Details
The raw residual is the observed effect minus the fitted mean. The summary reports its mean, standard deviation, root mean squared error and mean absolute error, plus the sum of squared Pearson residuals and internally studentized residual magnitudes. These are descriptive diagnostics, not a second heterogeneity test. Studentization conditions on fitted covariance and fixed-effect leverage; it is not an externally studentized deletion diagnostic.
Shapiro-Wilk is applied to finite whitened residuals (at most the first 5,000) when at least three nonconstant values exist. Its p-value is an exploratory screen: whitening and estimation of the mean/covariance do not make fitted residuals an independent sample with known parameters.
The heteroscedasticity screen correlates absolute raw residuals with fitted means and fits an ordinary linear trend. It requires at least three finite observations and variation in both quantities. An intercept-only mean model has constant fitted values, so this diagnostic is unavailable; the NA entries do not indicate a fitting failure. The ordinary-regression p-value does not adjust for within-study dependence, fitted-model selection or multiple screens. A nonsignificant result does not establish homoscedasticity or normality.
Value
A list containing residual vectors, global summaries, and optional grouped summaries. Normality and heteroscedasticity tables include status and reason fields explaining unavailable calculations; their numeric entries remain NA when the diagnostic cannot be computed. The printed model summary omits unavailable normality and heteroscedasticity screens; these tables retain the explanation for direct inspection with residual_diagnostics().
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
residual_diagnostics(fit)
Residuals for MARS Models
Description
Compute model residuals from a mars object with optional scaling.
Usage
## S3 method for class 'mars'
residuals(
object,
type = c("raw", "pearson", "studentized", "whitened", "standardized"),
...
)
Arguments
object |
A fitted |
type |
Residual type. One of |
... |
Not used. |
Value
A numeric vector of residuals.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
residuals(fit, type = "pearson")
Random Forest Variable Importance
Description
Returns aggregated split-based variable importance for a fitted
mars_rf
object.
Usage
rf_importance(object, scale = NULL, ...)
## S3 method for class 'mars_rf'
rf_importance(
object,
scale = NULL,
type = c("split", "permutation"),
validation = NULL,
folds = 5L,
repeats = 5L,
seed = 1L,
...
)
Arguments
object |
A fitted |
scale |
Logical or NULL. For split importance, NULL defaults to TRUE and returns relative importance summing to one when any reduction is positive. Permutation importance defaults to FALSE and cannot be normalized this way. |
... |
Additional arguments are rejected. |
type |
Split-loss importance or held-out grouped permutation importance. |
validation |
Optional |
folds, repeats, seed |
Controls for grouped validation when validation is NULL. |
Details
Split importance omits terminal linear coefficients and can favor variables with many candidate splits. Permutation importance measures changes in held-out squared error, includes terminal prediction contributions, and is not a significance test. Correlated moderators may share importance.
Value
A data frame of variable importance values.
Examples
rf_fit <- mars_rf_univariate(
data = teacher_expectancy,
formula = yi ~ year + weeks,
studyID = "study",
variance = "vi",
num_trees = 25,
seed = 123
)
rf_importance(rf_fit)
Risk-of-Bias Traffic Light and Aggregate Bar Plot
Description
Draws a study-level traffic-light plot of risk-of-bias judgments and a component-level stacked bar plot of percentages (Low, Unclear, High).
Usage
risk_of_bias_plot(
data,
study,
component,
decision,
study_order = NULL,
component_order = NULL,
main_traffic = "Risk of Bias (Study Level)",
main_aggregate = "Risk of Bias by Component (%)",
low_col = "#2E8B57",
unclear_col = "#F0C419",
high_col = "#C0392B",
cex_axis = 0.85,
cex_main = 1,
study_legend_position = "top",
aggregate_legend_position = "top",
study_legend_title = NULL,
aggregate_legend_title = NULL,
legend_inset = c(0, -0.13),
main_traffic_adj = 0.5,
main_aggregate_adj = 0.5,
plot = c("both", "study", "aggregate"),
separate_plots = FALSE,
aggregate_horizontal = FALSE
)
Arguments
data |
A data frame in long format. |
study |
Character string naming the study ID column. |
component |
Character string naming the risk-of-bias component/domain column. |
decision |
Character string naming the judgment column. Values are
matched to |
study_order |
Optional character vector with custom study order. |
component_order |
Optional character vector with custom component order. |
main_traffic |
Title for the traffic-light panel. |
main_aggregate |
Title for the aggregate stacked-bar panel. |
low_col |
Color used for low risk. |
unclear_col |
Color used for unclear risk. |
high_col |
Color used for high risk. |
cex_axis |
Axis text scaling. |
cex_main |
Main title scaling. |
study_legend_position |
Legend position for the study panel. Use
|
aggregate_legend_position |
Legend position for the aggregate panel.
Use |
study_legend_title |
Optional legend title for the study panel. |
aggregate_legend_title |
Optional legend title for the aggregate panel. |
legend_inset |
Numeric legend inset passed to |
main_traffic_adj |
Horizontal title alignment in |
main_aggregate_adj |
Horizontal title alignment in |
plot |
Which panel(s) to draw: |
separate_plots |
Logical. If |
aggregate_horizontal |
Logical. If |
Details
Input data must be in long format with one row per study-component judgment.
Value
Invisibly returns a list containing:
- decision_matrix
Study x component matrix with values
"Low","Unclear", or"High".- counts
Component x decision count matrix.
- percentages
Component x decision percentage matrix (rows sum to 100).
Examples
rob_dat <- data.frame(
study = rep(paste0("Study_", 1:5), each = 4),
component = rep(c("Randomization", "Allocation", "Blinding", "Attrition"), 5),
decision = c(
"Low", "Low", "Unclear", "High",
"Low", "Unclear", "Unclear", "High",
"High", "High", "Unclear", "Low",
"Low", "Low", "Low", "Low",
"Uncler", "Low", "High", "Unclear"
),
stringsAsFactors = FALSE
)
risk_of_bias_plot(
data = rob_dat,
study = "study",
component = "component",
decision = "decision",
plot = "aggregate",
aggregate_horizontal = TRUE
)
Cluster-robust Wald test for MARS coefficients
Description
Cluster-robust Wald test for MARS coefficients
Usage
robust_wald(
object,
constraints,
null = 0,
test = c("HTZ", "Naive-F", "chi-square")
)
Arguments
object |
A fitted |
constraints |
A constraint matrix, coefficient names, or coefficient indices. |
null |
Numeric null values. |
test |
One of |
Examples
fit <- mars(school, studyID = "study", formula = effect ~ year,
variance = "var", varcov_type = "univariate", structure = "univariate",
estimation_method = "MLE", robustID = "district")
robust_wald(fit, constraints = 2)
Jackknife mars wrapper
Description
This is a wrapper around mars() to perform leave-one-out jackknife
estimation for a single omitted unit.
Usage
sample_jackknife(
leave_out,
data,
studyID,
effectID = NULL,
sample_size = NULL,
effectsize_type = NULL,
formula = NULL,
variable_names = NULL,
effectsize_name = NULL,
estimation_method = NULL,
variance = NULL,
varcov_type = NULL,
weights = NULL,
structure = NULL,
intercept = FALSE,
missing = "remove",
optim_method = "L-BFGS-B",
robustID = NULL,
multivariate_covs = NULL,
jackknife_target = c("complete_data", "beta_selection", "beta_binomial",
"logistic_selection"),
publication_bias_args = list(),
lasso = FALSE,
lasso_args = list(),
tol = NULL,
...
)
Arguments
leave_out |
Unit to omit from the dataset. For single-level models this with one row per study this is a row index. Otherwise it is a study ID, outermost random-group value, or robustID value, matching replicate_jackknife(). |
data |
Data used for analysis. |
studyID |
Character string representing the study ID. |
effectID |
Character string representing the effect size ID. |
sample_size |
Character string representing the sample size of the studies. |
effectsize_type |
Type of effect size being analyzed. |
formula |
The formula used for specifying the fixed and random structure. |
variable_names |
Vector of character strings representing the attributes with correlations. The attributes that are correlated should be separated by an underscore. |
effectsize_name |
Character string representing the name of the effect size column in the data. |
estimation_method |
Estimator. NULL uses REML for ordinary models and MLE for LASSO. |
variance |
Character string representing the variance column name. |
varcov_type |
Type of variance covariance matrix computed. |
weights |
User specified matrix of weights for analysis. |
structure |
Between-study covariance structure; NULL infers it from formula. |
intercept |
Whether a model intercept should be specified. |
missing |
Whether missing data should be removed, or kept. |
optim_method |
Optimization method passed to |
robustID |
A character vector specifying the cluster group to use for robust standard errors. |
multivariate_covs |
A one-sided formula for multivariate analysis covariates. |
jackknife_target |
Analysis to fit after each leave-one-out omission.
Use |
publication_bias_args |
Optional named list of extra arguments passed to
|
lasso |
Refit mars_lasso(); summaries describe selection stability. |
lasso_args |
Named controls for mars_lasso(), such as folds and selection. |
tol |
NULL retains the fitting engine's default tolerance. |
... |
Additional arguments passed to |
Examples
jack_fit <- sample_jackknife(
leave_out = 1,
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
Modified School Calendar Meta-analysis Data
Description
Results from studies of modified school calendars and student achievement. The effect sizes are nested within school districts, making the data useful for multilevel meta-analysis, scale-location models, alternative estimation workflows, and diagnostics examples in mars.
Usage
school
Format
A data frame with 56 rows and 5 columns:
- district
School district identifier.
- study
Study identifier within district.
- effect
Standardized reading-achievement effect size comparing year-round and traditional school calendars.
- var
Within-study sampling variance of
effect.- year
Year when the study was performed.
Source
Konstantopoulos, S. (2011). Fixed effects and variance components estimation in three-level meta-analysis. Research Synthesis Methods, 2(1), 61-76. The data are also distributed with the mixmeta package.
Examples
school
Selection-Function Plot for Publication-Bias Models
Description
Draws the estimated selection function (selection weight versus p-value)
from a fitted pub_bias object.
Usage
selection_plot(object, ...)
## S3 method for class 'pub_bias'
selection_plot(
object,
normalize = TRUE,
p_grid = seq(0.001, 0.999, length.out = 200),
line_col = "#C0392B",
line_lwd = 2,
bar_col = "#F3A683",
border_col = "#B23A2B",
xlab = "P-value",
ylab = NULL,
main = "Estimated Selection Function",
main_adj = 0.5,
main_line = NULL,
...
)
## S3 method for class 'pub_bias'
plot(x, type = c("funnel", "selection"), ...)
Arguments
object |
A fitted object returned by |
... |
Additional arguments passed to |
normalize |
Logical; TRUE divides weights by the largest weight on the plotted grid or among bins. FALSE returns the beta kernel, logistic weight or beta-binomial shape weight directly. Scaling does not identify absolute publication probabilities. Normalized values can depend on the plotted grid. |
p_grid |
Numeric vector of p-values where the selection function is evaluated for continuous methods. |
line_col |
Line color used for continuous selection models. |
line_lwd |
Line width used for continuous selection models. |
bar_col |
Fill color used for bin bars when
|
border_col |
Border color for bin bars. |
xlab |
X-axis label. |
ylab |
Optional y-axis label. |
main |
Plot title. |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
x |
A fitted object returned by |
type |
Plot type: |
Details
The plot describes the assumed fitted selection shape. Neither a nonconstant curve nor an adjusted effect establishes publication bias. For nonconverged or unidentified fits, curves are candidate sensitivity shapes. Extreme unnormalized kernels can overflow; use normalize=TRUE to display their relative shape stably. Beta-binomial bars span the equal-width p bins.
Value
Invisibly returns evaluated p/bin coordinates and weight_plot.
Examples
fit <- mars(
data = teacher_expectancy,
studyID = "study",
effectID = NULL,
sample_size = NULL,
formula = yi ~ 1,
variance = "vi",
varcov_type = "univariate",
structure = "univariate"
)
bias_fit <- publication_bias(fit)
selection_plot(bias_fit)
Simulated Multivariate Standardized Mean Difference Data
Description
Simulated standardized mean difference data with multiple outcomes nested within studies. The data are used in examples for multivariate SMD workflows and methodology-adjusted substantive meta-regression.
Usage
smd_data
Format
A data frame with 14 rows and 7 columns:
- study
Study identifier.
- d
Observed standardized mean difference.
- SE
Standard error of
d.- N
Total study sample size.
- nt
Treatment-group sample size.
- nc
Control-group sample size.
- r2do
Assumed within-study outcome correlation used when building SMD covariance matrices.
Source
Simulated for package examples; see data-raw/smd-data-sim.r
in the source repository for the data-generation code.
Examples
smd_data
Summarize fitted SMD and HSMD models
Description
Summarize fitted SMD and HSMD models
Usage
## S3 method for class 'hsmd'
summary(object, ...)
Arguments
object |
A fitted |
... |
Arguments passed to each underlying |
Details
Inference remains conditional on the CV benchmarks. Options are checked separately for each fitted model; no resampling or refitting occurs.
Value
A named list of model summaries with a benchmark-uncertainty note.
Summarize an ordinary MARS fit
Description
Summarize an ordinary MARS fit
Usage
## S3 method for class 'mars'
summary(
object,
fit_measures = TRUE,
digits = max(3, getOption("digits") - 3),
vcov_method = NULL,
inference = NULL,
test = NULL,
robust_type = NULL,
hksj_adjust = NULL,
cluster = NULL,
level = 0.95,
...
)
Arguments
object |
A fitted ordinary |
fit_measures |
Retained for compatibility. |
digits |
Display precision. |
vcov_method |
Optional |
inference |
NULL preserves the usual summary; |
test |
NULL uses normal model inference or the stored robust test.
Options are |
robust_type |
Optional robust covariance, such as |
hksj_adjust |
|
cluster |
Optional column name in the fitted analysis data identifying independent robust clusters. Defaults to the stored robust clustering column. |
level |
Pointwise confidence level for location and scale coefficients, default 0.95. |
... |
Reserved; unused arguments are rejected. |
Details
Summary inference does not refit or modify the fitted object. The default
retains the existing model and, where fitted, robust coefficient tables.
An explicit selection returns one selected coefficient table, including df,
and inference_details with its covariance, method and adjustment.
Model t and HKSJ require independent univariate models without a scale
formula. HKSJ additionally requires estimated heterogeneity and GLS covariance;
its multiplier is the fitted weighted residual sum of squares divided by n-p.
Model-based Satterthwaite uses conditional GLS covariance, covariance
derivatives and inverse expected ML/REML covariance-parameter information:
\mathrm{df}=2v^2/(g'I^{-1}g), where v is a coefficient variance
and g is its gradient.
It supports interior, identifiable ordinary univariate, multivariate and
multilevel covariance models; location-scale and fixed-heterogeneity fits
are excluded. This expected-information approximation is distinct from
observed-Hessian Satterthwaite and from robust CR2/Satterthwaite.
Robust overrides require independent clusters and never silently fall back
from a requested covariance type. Unsupported combinations raise errors.
Only mean-coefficient inference changes: existing heterogeneity, scale,
prediction, joint model-fit tests and downstream analyses are unchanged.
Bootstrap, jackknife and permutation computations remain explicit through
mars_alt_estimation() and their own summary methods.
Use the same options in confint.mars() for matching coefficient intervals.
Value
A native MARS summary including covariance method and optimizer status.
References
Tipton, E. (2015). Small sample adjustments for robust variance estimation with meta-regression. Psychological Methods, 20(3), 375–393. doi:10.1037/met0000011.
Pustejovsky, J. E., and Tipton, E. (2018). Small-sample methods for cluster-robust variance estimation and hypothesis testing in fixed effects models. Journal of Business & Economic Statistics, 36(4), 672–683. doi:10.1080/07350015.2016.1247004.
Sidik, K., and Jonkman, J. N. (2002). A simple confidence interval for meta-analysis. Statistics in Medicine, 21(21), 3153–3159. doi:10.1002/sim.1262.
Knapp, G., and Hartung, J. (2003). Improved tests for a random effects meta-regression with a single covariate. Statistics in Medicine, 22(17), 2693–2710. doi:10.1002/sim.1482.
Röver, C., Knapp, G., and Friede, T. (2015). Hartung-Knapp-Sidik-Jonkman approach and its modification for random-effects meta-analysis with few studies. BMC Medical Research Methodology, 15, 99. doi:10.1186/s12874-015-0091-1.
See Also
mars_inference_options for the model compatibility table and supported argument combinations.
Summarize pooled accuracy and paired diagnostic contrasts
Description
Summarize pooled accuracy and paired diagnostic contrasts
Usage
## S3 method for class 'mars_dta_paired'
summary(object, level = 0.95, ...)
## S3 method for class 'summary.mars_dta_paired'
print(x, ...)
Arguments
object |
A fitted |
level |
Confidence level between zero and one. |
... |
For |
x |
A summary returned by |
Details
Pooled sensitivity and specificity are inverse logits of the fitted mean logits for Gaussian fits. Multinomial fits sum the relevant joint probabilities at zero study effects. Their intervals use a delta approximation based on the observed information, with missing limits when that information cannot be inverted. Contrasts compare the second test with the first test within each endpoint. They report an absolute difference in pooled probabilities and the ratio of pooled odds. The intervals use the full fixed-effect covariance, including the covariance between tests. Odds-ratio intervals are formed on the log scale. Absolute differences use the delta method with Wald limits that can extend outside the range from -1 to 1.
Value
A summary with a pooled table of sensitivity and specificity
and a contrasts table comparing the two tests, plus the number of
studies, estimation method, and between-study covariance. Multinomial
summaries also include the association odds ratios between tests.
Summarize and plot threshold-specific diagnostic accuracy
Description
Summarize and plot threshold-specific diagnostic accuracy
Usage
## S3 method for class 'mars_dta_thresholds'
summary(object, level = 0.95, ...)
## S3 method for class 'mars_dta_thresholds'
predict(object, thresholds = NULL, level = 0.95, ...)
## S3 method for class 'mars_dta_thresholds'
plot(
x,
...,
xlim = c(0, 1),
ylim = c(0, 1),
xlab = "False-positive rate",
ylab = "Sensitivity",
labels = TRUE,
thresholds = NULL,
type = if (identical(x$family, "multinomial")) "l" else "p"
)
Arguments
object, x |
A fitted |
level |
Confidence level between zero and one. |
... |
Graphical arguments passed to |
thresholds |
Numeric vector of cutoffs for prediction or plotting. Defaults to the observed cutoffs for predictions and Gaussian plots. Multinomial plots default to a grid spanning the observed cutoffs. Gaussian predictions require reported cutoffs. |
xlim, ylim, xlab, ylab |
Axis limits and labels for the ROC plot. |
labels |
Logical. Label each operating point with its reported cutoff. |
type |
Plot type passed to |
Details
The summary gives inverse logits of the fitted means and pointwise
Wald confidence intervals. The ROC plot places these fitted operating
points at one minus specificity and sensitivity. Multinomial predictions
evaluate the logistic distributions at the mean study locations. They
flag extrapolation beyond the observed cutoff range. Their pointwise
Wald intervals use the observed information when available and have
missing limits otherwise. For a latent-threshold summary curve from a
single-test bivariate fit, see dta_sroc().
Value
summary() returns a list with a pooled data frame, the
number of studies, estimation method and between-study covariance.
The table includes the number of studies reporting each cutoff.
predict() returns a data frame with accuracy and interval limits.
plot() invisibly returns the coordinates of the plotted points.
Summarize and Plot a Penalized MARS Model
Description
Summarize and Plot a Penalized MARS Model
Usage
## S3 method for class 'mars_lasso'
summary(object, ...)
## S3 method for class 'summary.mars_lasso'
print(x, digits = 4L, ...)
## S3 method for class 'mars_lasso'
print(x, digits = 4L, ...)
## S3 method for class 'mars_lasso'
plot(x, type = c("cv", "coefficients"), ...)
Arguments
object, x |
Fitted mars_lasso object or its summary, as appropriate. |
... |
Additional graphical parameters for plot; unsupported summary and print arguments are rejected. |
digits |
Significant digits to print. |
type |
cv plots validation scores and approximate fold standard errors; coefficients plots the supplied-unit coefficient path. Zero lambdas use a linear horizontal axis; positive-only paths use a logarithmic axis. |
Details
Selected-model coefficients have no ordinary Wald tests or intervals. The approximate 1se tuning threshold is not a confidence interval. Variance components are conditional ML point estimates under the penalized mean model.
Value
Summary returns point estimates, variance components, tuning scores and diagnostics. Print and plot return their input invisibly.
Summarize repeated-effects models with optional coefficient inference
Description
Summarize repeated-effects models with optional coefficient inference
Usage
## S3 method for class 'mars_repeated'
summary(
object,
inference = NULL,
test = NULL,
robust_type = NULL,
cluster = NULL,
hksj_adjust = NULL,
level = 0.95,
...
)
Arguments
object |
A fitted |
inference |
NULL preserves the usual summary; |
test |
NULL uses normal model inference or the stored robust test.
Options are |
robust_type |
Optional robust covariance, such as |
cluster |
Optional column name in the fitted analysis data identifying independent robust clusters. Defaults to the stored robust clustering column. |
hksj_adjust |
|
level |
Pointwise confidence level for location and scale coefficients, default 0.95. |
... |
Reserved; unused arguments are rejected. |
Details
Model normal, expected-information Satterthwaite and cluster-robust inference are supported. Model Satterthwaite requires positive estimated common heterogeneity. Default robust clustering is by study. HKSJ and residual-df model t inference are unsupported for dependent effects. Overrides affect only coefficient tests and confidence intervals in a copy.
Value
A mars_repeated copy with a coefficient table and inference metadata.
See Also
mars_inference_options for model-specific restrictions.
Standardized Report for Correlation Synthesis and Latent Factors
Description
Builds a standardized report object with pooled correlations, uncertainty, heterogeneity summaries, latent-factor solution tables, publication-ready tables, plot-ready matrices, reproducibility metadata, and limitations.
Usage
synthesis_factor_report(
mars_object,
factor_method = c("none", "efa", "cfa"),
n_factors = 1L,
cfa_model = NULL,
group_var = NULL,
loading_threshold = 0.3,
synthesis_method = c("model", "average", "weighted"),
synthesis_transform = c("none", "fisher_z"),
missing_corr = c("available", "pairwise", "em"),
attenuation = c("none", "correct"),
reliability = NULL,
reliability_missing = c("error", "skip", "impute_mean", "assume_1"),
missing_sensitivity = FALSE,
attenuation_sensitivity = FALSE,
reliability_scenarios = NULL,
pd_adjust = c("none", "eigen_clip", "nearpd"),
pd_tol = 1e-08,
include_publication_bias = TRUE,
vcov_source = c("model", "robust"),
...
)
## S3 method for class 'synthesis_report'
summary(object, ...)
## S3 method for class 'synthesis_report'
print(x, digits = max(3, getOption("digits") - 3), ...)
## S3 method for class 'synthesis_report'
plot(
x,
type = c("pooled_r", "heterogeneity", "residuals", "calibration", "loadings", "path",
"influence", "influence_heatmap", "invariance"),
main = NULL,
main_adj = 0.5,
main_line = NULL,
invariance_legend_position = "bottomleft",
invariance_legend_title = NULL,
path_center_latent = TRUE,
path_latent_x = NULL,
path_observed_x = NULL,
path_latent_span = c(0.2, 0.8),
path_observed_span = c(0.1, 0.9),
path_latent_y = 0.8,
path_observed_y = 0.2,
path_latent_cex = 1,
path_observed_cex = 0.9,
path_arrow_col = "gray40",
path_arrow_lwd = 1,
path_arrow_length = 0.08,
path_loading_cex = 0.75,
path_latent_min_gap = 0.06,
path_covariances = TRUE,
path_residuals = TRUE,
path_factor_variances = TRUE,
path_digits = 3,
...
)
Arguments
mars_object |
A fitted object returned by |
factor_method |
One of |
n_factors |
Number of factors when |
cfa_model |
Lavaan-style latent model syntax when
|
group_var |
Retained for compatibility. When supplied, the report explains that multi-group invariance testing is unavailable. Separate group synthesis and joint estimation are required. |
loading_threshold |
Absolute-value threshold used to flag salient loadings in publication-ready tables. |
synthesis_method |
Correlation synthesis method: |
synthesis_transform |
Optional pooling transform for
|
missing_corr |
Missing-correlation handling for synthesized matrices.
One of |
attenuation |
Attenuation-correction mode for synthesized correlations.
One of |
reliability |
Reliability input used when |
reliability_missing |
Strategy for missing reliability values.
One of |
missing_sensitivity |
Logical; if |
attenuation_sensitivity |
Logical; if |
reliability_scenarios |
Optional named list of reliability inputs used
when |
pd_adjust |
Positive-definite repair for synthesized correlations:
|
pd_tol |
Minimum eigenvalue tolerance used by
|
include_publication_bias |
Logical; if |
vcov_source |
|
... |
Additional graphical arguments passed to the underlying plotting functions. |
object |
An object of class |
x |
An object of class |
digits |
Number of digits used when printing numeric tables. |
type |
Plot type to display. One of |
main |
Optional plot title. |
main_adj |
Horizontal title alignment in |
main_line |
Optional title line. If |
invariance_legend_position |
Legend position for the invariance plot, or |
invariance_legend_title |
Optional legend title for the invariance plot. |
path_center_latent |
Logical; if |
path_latent_x |
Optional numeric vector of x positions for latent variables in the path diagram. |
path_observed_x |
Optional numeric vector of x positions for observed indicators in the path diagram. |
path_latent_span |
Numeric length-2 vector giving the horizontal span used for latent nodes when positions are generated automatically. |
path_observed_span |
Numeric length-2 vector giving the horizontal span used for observed nodes when positions are generated automatically. |
path_latent_y |
Vertical position for latent nodes in the path diagram. |
path_observed_y |
Vertical position for observed nodes in the path diagram. |
path_latent_cex |
Text scaling for latent-node labels. |
path_observed_cex |
Text scaling for observed-node labels. |
path_arrow_col |
Arrow color for the path diagram. |
path_arrow_lwd |
Arrow line width for the path diagram. |
path_arrow_length |
Arrowhead length for the path diagram. |
path_loading_cex |
Text scaling for path loading labels. |
path_latent_min_gap |
Minimum horizontal spacing enforced between latent nodes when positions are generated automatically. |
path_covariances |
Show nonzero latent covariances in CFA path plots. |
path_residuals |
Show observed-indicator residual variance loops in CFA path plots. |
path_factor_variances |
Show latent variances in a caption, marking fixed values. |
path_digits |
Number of decimal places for CFA path parameter labels. Labels use the fitted (unstandardized) parameter scale. Unit factor variances make factor covariances equal correlations. Latent variances are disturbance variances when structural regressions predict factors. |
Details
Correlation intervals are pointwise normal intervals centered on each pooled
correlation, using the matched coefficient covariance; endpoints may exceed
[-1,1] under this approximation. Alternative pooling and repaired matrices
have no matched sampling covariance, so their intervals are NA. Heterogeneity
entries are between-study standard deviations, not sampling standard errors.
CFA defaults to correlation-structure WLS when matched covariance is available. The loading table distinguishes raw marker-scaled and standardized loadings; salient CFA loadings use the standardized values. EFA communalities and implied matrices include oblique factor correlations. Optional EFA loading uncertainty and CFA WLS uncertainty are retained in the report tables and factor fit.
Model-based leave-one-study-out influence refits the original synthesis specification. Average/weighted pooling is recomputed on the reduced data. Attenuation, missing-correlation and repair options are preserved. Frobenius change measures the matrix-wide shift; maximum absolute change measures the largest cell shift. Neither is a significance test. Failed refits are labelled with NA shifts, estimability and reasons. Objects without a stored model-refit specification cannot provide model-based study influence.
Optional parallel analysis is descriptive sensitivity, not calibrated factor
retention inference. Multi-group invariance testing is unavailable: valid tests
require separately synthesized group matrices, their joint sampling covariance,
and shared-parameter estimation. Supplying group_var returns this explanation.
Publication-bias checks are exploratory and do not establish selective reporting.
See path_model() and efa_from_synthesis() for inference assumptions and limits.
Value
An object of class synthesis_report.
Examples
fit <- mars(
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"
)
)
report <- synthesis_factor_report(fit, factor_method = "efa", n_factors = 1)
summary(report)
Tau U effect size
Description
Tau U effect size and variance computation.
Usage
tau_u_computation(
data,
studyID,
subjectID,
outcome_name,
phase_name,
phase_order = NULL,
version = c("revised", "original"),
baseline_trend_adjust = TRUE,
variance_correction = c("none", "small_sample", "autocorrelation", "both"),
na_option = "listwise"
)
Arguments
data |
Raw data to compute the effect sizes and variances from |
studyID |
A character string representing the studyID |
subjectID |
A character string representing the subjectID |
outcome_name |
A character string representing the outcome name |
phase_name |
A character string representing the phase name |
phase_order |
Optional character vector of length 2 giving the baseline
phase first and the comparison phase second. If |
version |
Character string selecting the baseline-trend-corrected Tau-U
denominator. |
baseline_trend_adjust |
Logical. If |
variance_correction |
Character string selecting an optional
multiplicative correction for the three variance approximations.
|
na_option |
Currently only |
Details
Tau-U is computed by contrasting the first phase in phase_order with the
second. Supplying phase_order is recommended whenever the intended baseline
and intervention labels are known. Each study-subject combination must
contain observations from both phases. baseline_trend_adjust = TRUE
computes the baseline-trend-corrected Tau-U; baseline_trend_adjust = FALSE
computes the unadjusted A-vs-B nonoverlap Tau. For baseline-trend-corrected
Tau-U, the revised denominator uses mn, while the original denominator
adds the baseline trend term m(m-1)/2.
Let m be the number of baseline observations, n the number of comparison
observations, Q_P the vector of pairwise phase-contrast signs comparing
comparison observations to baseline observations, and Q_A the strictly
upper-triangular baseline self-comparison signs used for the baseline trend
adjustment. The Tau-U numerator is
N_U = \sum Q_P - I_{\mathrm{trend}} \sum Q_A,
where I_{\mathrm{trend}}=1 when baseline_trend_adjust = TRUE and 0 otherwise.
The reported Tau-U is
\tau_U = N_U / d,
where d=mn for the revised version and for all unadjusted A-vs-B Tau
values. The original baseline-trend-corrected version instead uses
d=mn+m(m-1)/2. The revised denominator keeps Tau-U on the
A-vs-B nonoverlap scale after removing baseline trend; the original
denominator normalizes by all pairwise comparisons entering the adjusted
numerator.
With fixed phase sizes and a fixed adjustment choice, v3 is the exact
variance of the stated statistic under the independent, continuous,
common-distribution null, before optional multipliers. Under that null,
v2 is exact for the phase component (\sum Q_P)/d only; when adjustment is
enabled it omits uncertainty from baseline trend. Ties, phase differences,
temporal trends, and serial dependence depart from these assumptions; the
theoretical formulas do not include tie corrections. Data-dependent selection
of baseline adjustment requires a separate variance analysis.
The empirical variance approximation v1 is
\widehat{\mathrm{Var}}(\tau_U) =
\frac{\widehat{\mathrm{Var}}(Q_P) \, (m n) +
\widehat{\mathrm{Var}}(Q_A) \, m (m - 1) / 2}{d^2},
where d=mn for the revised version and
d=mn+m(m-1)/2 for the original baseline-trend-corrected version.
When baseline_trend_adjust = FALSE, the Q_A term is omitted and
d=mn. This is a working-independence approximation: it omits
covariance among comparisons sharing observations and between components.
Even independent observations produce dependent signs. For two phase signs
sharing a baseline observation, the covariance is 1/3 under the strict null.
Consequently, empirical sign dispersion times the comparison count need not
estimate the variance of the sum. v1 already uses signed comparisons and
requires no count-to-sign scaling correction.
The Mann-Whitney-style theoretical variance approximation v2 is
\mathrm{Var}(\tau_U) =
\frac{m n (m + n + 1) / 3}{d^2},
using the same denominator d.
The phase-contrast variance approximation v3 adds the baseline-trend
component when baseline_trend_adjust = TRUE:
\mathrm{Var}_{\mathrm{pc}}(\tau_U) =
\frac{m n (m + n + 1) / 3 + m (m - 1) (2 m + 5) / 18}{d^2},
again with d=mn for the revised version and
d=mn+m(m-1)/2 for the original baseline-trend-corrected version.
When baseline_trend_adjust = FALSE, the baseline-trend component is omitted,
so v2 and v3 are identical before optional corrections.
To derive the scale, write P=\sum Q_P and Q=\sum Q_A.
Let U count cross-phase pairs with B_j>A_i, and W count baseline
pairs with A_k>A_i for i<k in chronological row order. Without ties,
P = 2U - mn, \qquad Q = 2W - \binom{m}{2}.
Under the strict null, each count indicator has variance 1/4. Cross-phase indicators sharing one observation have covariance 1/12, giving
\mathrm{Var}(U) = mn/4 + 2[m\binom{n}{2} + n\binom{m}{2}]/12
= mn(m+n+1)/12.
For each baseline triple the three indicator covariances are
1/12, -1/12, 1/12, giving
\mathrm{Var}(W) = \binom{m}{2}/4 + 2\binom{m}{3}/12
= m(m-1)(2m+5)/72.
Disjoint comparisons are independent. Multiplication by two multiplies variance by four, yielding signed-sum divisors 3 and 18 above. In general the numerator variance is
\mathrm{Var}(P-IQ) = \mathrm{Var}(P) + I\mathrm{Var}(Q)
- 2I\mathrm{Cov}(P,Q),
where I=I_{\mathrm{trend}}. Conditional on the unordered baseline values and all
comparison values, P is fixed and equally likely baseline time orders give
conditional mean zero for Q. Thus \mathrm{Cov}(P,Q)=0 under the strict null.
This argument does not establish exactness under the departures listed above.
Two optional corrections can be applied to all three approximate variances.
The small-sample correction multiplies the variances by
(m+n)/(m+n-1). This is a heuristic for Tau-U; it inflates v3
above its exact strict-null variance. The autocorrelation
correction estimates the lag-1 autocorrelation rho from the observed
within-case outcome sequence, in the order rows appear in data, and applies
the AR(1)-style design-effect multiplier
1 + 2 \sum_{k = 1}^{m+n-1} (1 - k / (m+n)) \rho^k.
This finite-series factor describes a stationary AR(1) sample mean;
applying it to Tau-U is an approximation. Raw-outcome correlation can reflect
phase shifts or trends as well as serial dependence. It differs from the
infinite-series factor (1+\rho)/(1-\rho) in short series.
Both optional multipliers are applied after the signed-scale base variances
and do not make the formulas exact for other data-generating processes.
Polynomial calibration is a separate methodological task; coefficients fitted
to a different base-variance scale require separate reanalysis and validation.
The package bounds this design-effect multiplier above zero before applying
it. If autocorrelation cannot be estimated, the autocorrelation multiplier is
set to 1 and autocorrelation is returned as NA. With
variance_correction = "both", the final multiplier is the product of the
small-sample and autocorrelation multipliers:
\widehat{\mathrm{Var}}_{\mathrm{corrected}}(\tau_U)
= c \widehat{\mathrm{Var}}(\tau_U).
Value
Returns a data frame that contains the studyID, subjectID,
and the Tau-U effect size and 3 different variance approximations:
v1 is an empirical signed-comparison variance approximation under working
independence. v2 is the theoretical null variance of the signed phase
component, omitting baseline trend variability. v3 adds the baseline-trend
component when requested. The theoretical formulas assume independent,
continuous observations from a common distribution.
The output also includes the lag-1 autocorrelation estimate used by the
optional autocorrelation correction, the selected correction label, and the
final variance multiplier applied to v1, v2, and v3.
Examples
scd <- data.frame(
study = "S1",
subject = "P1",
phase = rep(c("A", "B"), each = 4),
outcome = c(2, 3, 3, 4, 5, 6, 6, 7)
)
tau_u_computation(
scd,
studyID = "study",
subjectID = "subject",
outcome_name = "outcome",
phase_name = "phase",
phase_order = c("A", "B")
)
Teacher Expectancy Data
Description
Teacher expectancy intervention study data with observed effect sizes and variances.
Usage
teacher_expectancy
Format
A dataframe with 19 rows and 10 columns:
- study
Study identifier.
- author
Study author(s).
- year
Publication year.
- weeks
Duration of intervention in weeks.
- setting
Testing setting (
grouporindiv).- tester
Tester awareness (
awareorblind).- n1i
Treatment group sample size.
- n2i
Control group sample size.
- yi
Observed effect size.
- vi
Sampling variance of effect size.
Examples
teacher_expectancy
Transform effect estimates and propagate uncertainty
Description
Applies a named scalar transformation or a supplied differentiable function.
The original object is retained; specialized variance conventions in
compute_es() are not silently substituted for delta-method propagation.
Usage
transform_es(
x,
transformation,
derivative = NULL,
V = NULL,
target_scale = NULL,
jacobian = NULL,
output_ids = NULL,
conf_level = NULL,
errors = c("collect", "stop")
)
## S3 method for class 'mars_es_transform'
print(x, ...)
## S3 method for class 'mars_es_transform'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)
Arguments
x |
A mars_es or mars_es_transform object. |
transformation |
One of fisher_z, inverse_fisher, log, exp, logit, inverse_logit, or a function. Custom scalar functions are called once per estimate; with jacobian supplied, the function receives the full vector. |
derivative |
Required analytic derivative function for a custom scalar transformation. Not used for named or multivariate transformations. |
V |
Optional full sampling covariance matrix on the source scale. Defaults to x$sampling_covariance if available. An unnamed matrix follows source effect order; a named matrix must have both row/column effect IDs and is reordered to match. Its diagonal must agree with any finite source variances. It must be finite, symmetric and positive semidefinite. |
target_scale |
Required label (or one label per output) for custom transformations. Named transformations derive labels from the source scale. |
jacobian |
Optional analytic Jacobian function for a multivariate custom transformation. It returns an output-by-input matrix. A full V is required; missing covariances are never replaced with zeros. |
output_ids |
Optional unique output IDs for a multivariate transformation. Scalar transformations retain source effect IDs. |
conf_level |
Confidence level; defaults to the source setting or .95. |
errors |
collect returns per-row diagnostics; stop fails on incomplete scalar results. Invalid function definitions or covariance matrices always fail. |
... |
Additional arguments passed to print.data.frame or as.data.frame. |
row.names, optional |
Passed to as.data.frame. |
Details
Scalar variance is [f'(y_i)]^2v_i. Multivariate covariance is DVD^T.
These are first-order approximations for nonlinear functions. A zero derivative
is diagnosed rather than interpreted as zero uncertainty. No generic second-
order or bootstrap correction is inferred. Named Fisher transforms require
matching correlation/Fisher scales and never mix partial with semipartial r.
For example, transforming COR's variance gives 1/(n-1), not the specialized
ZCOR variance 1/(n-3). Transforming SPCOR to Fisher z agrees with ZSPCOR's
variance because both use the same semipartial delta formula. All returned
intervals are symmetric delta-Wald intervals on the target scale; they differ
from transforming source confidence endpoints. The display component of
compute_es already provides endpoint back-transformations for interpretation.
Transformations requiring additional uncertain parameters must include those parameters in the input vector and their full covariance in V. The caller must justify cross-metric model assumptions; calculus does not establish them.
Value
A mars_es_transform object with data (transformed estimates, variances and delta-Wald limits), original_result, provenance, diagnostics, settings, and sampling_covariance. Without a full source V, transformed marginal variances are available but sampling_covariance remains NULL.
References
Oehlert, G. W. (1992). A note on the delta method. The American Statistician, 46(1), 27–29. doi:10.1080/00031305.1992.10475842.
Examples
x <- compute_es(data.frame(r=.3, n=100), measure="COR",
design="independent_observations", input="correlation", r=r, n_total=n)
transform_es(x, "fisher_z")
Trim-and-Fill Sensitivity Analysis
Description
Iteratively trims asymmetric extreme studies, estimates a symmetry center, reflects their effects to impute studies and refits the augmented meta-analysis. Implemented using base R; no additional runtime package is required.
Usage
trim_fill(
object,
side = c("auto", "left", "right"),
estimator = c("L0", "R0", "Q0"),
maxiter = 100L,
tol = 1e-08,
level = 0.95
)
## S3 method for class 'mars_trimfill'
print(x, digits = 4L, ...)
Arguments
object |
Intercept-only univariate mars fit with one independent effect per study, or pub_bias fit whose ordinary parent is used. Moderator, multilevel, multivariate, scale-location, network and penalized models are unsupported. |
side |
auto, left or right: the side on which studies are imputed. auto fits a raw-effect meta-regression on sampling SE with the parent's ML/REML covariance convention; negative SE slope chooses right, otherwise left. This is data-driven and is not an Egger significance test. Prespecifying a scientifically meaningful side and checking both directions is preferable. |
estimator |
Missing-study rank estimator: L0 (default), R0 or Q0. |
maxiter |
Positive integer maximum number of trim/refit iterations. |
tol |
Numerical tolerance in (0,1) for scalar heterogeneity optimization. |
level |
Confidence level in (0,1) for conventional normal-reference intervals. |
x |
Trim-and-fill result. |
digits |
Significant digits for printing. |
... |
Unsupported print arguments are rejected. |
Details
For n observed studies, orient effects so the candidate missing side
is left, and sort ascending. At each iteration refit after excluding the
current number of largest effects. Rank absolute deviations from that center
using sequential ranks for ties; signed ranks use the deviation sign.
If T is the sum of positive signed ranks and r_- the largest absolute
negative rank, the estimates are L_0=(4T-n(n+1))/(2n-1),
R_0=n-r_{-}-1, and Q_0=n-1/2-\sqrt{2n^2-4T+1/4}.
Round to the nearest integer and truncate at zero. An all-zero-deviation
configuration yields zero. Stop when the estimated count stabilizes.
Negative Q0 radicands, fewer than two retained studies, cycles or iteration
exhaustion are errors, not successful adjustments. At least three input studies
are required. Reflect the largest n_imputed effects around the converged trimmed
center, restore their original direction and refit all observed and filled data.
Observed records keep their input order. Ties follow sorted effect order.
Each trimmed and augmented fit re-estimates constant heterogeneity by the
parent's ML or REML method. REML adds \log|X'V^{-1}X| to the concentrated normal
deviance; ML omits it. Scalar optimization compares an exact \tau^2=0 boundary.
A parent fixed \tau^2 is held fixed, including zero. Parent robust inference does
not transfer to imputed studies: displayed intervals are conventional normal
intervals conditional on the augmented data, omitting uncertainty in the
missing-study count and imputation. Both original and augmented summaries
use inverse-variance mean SEs, 1/\sqrt{\sum_i 1/(v_i+\tau^2)}, rather than copying
parent joint-Hessian or robust SEs; their intervals can differ from summary(parent).
No missing-count SE or bias-test p-value
is reported. L0, R0 and Q0 can produce materially different sensitivity results.
Filled points are hypothetical studies under funnel symmetry, not recovered unpublished observations or a verified count of missing studies. Heterogeneity, effect-SE coupling, direction choice and rank ties can affect the result. Sequential tie ranks can give positive fills even for exactly symmetric paired data; that count is not proof of missing studies. Zero imputed studies does not exclude publication bias. The algorithm follows the Duval–Tweedie rank/reflection construction; matched ML/REML, side and estimator settings can be compared with metafor::trimfill().
Value
A mars_trimfill object with n_imputed, side, estimator, original and
adjusted estimate/SE/tau2/interval summaries, reflection_center, iteration
history, augmented data, source-row links and diagnostics. Filled records have
imputed=TRUE and retain the sampling variance of their reflected source study.
The ordinary parent is unchanged. funnel_plot() distinguishes filled points.
References
Duval and Tweedie (2000). Trim and fill: A simple funnel-plot-based method of testing and adjusting for publication bias in meta-analysis. Biometrics, 56, 455-463. doi:10.1111/j.0006-341X.2000.00455.x.
Examples
fit <- mars(bcg,studyID="trial",effectID=NULL,sample_size=NULL,formula=yi~1,
variance="vi",varcov_type="univariate",structure="univariate")
sensitivity <- trim_fill(fit,side="left")
sensitivity
funnel_plot(fit,trim_fill=TRUE,trim_fill_args=list(side="left"))
Extract a model-based or cluster-robust covariance matrix
Description
Extract a model-based or cluster-robust covariance matrix
Usage
## S3 method for class 'mars'
vcov(
object,
type = c("model", "robust"),
robust_type = c("selected", "CR0", "CR1", "CR1S"),
vcov_method = NULL,
...
)
Arguments
object |
A fitted |
type |
Either |
robust_type |
Optional stored robust variant: |
vcov_method |
Optional model covariance override: |
... |
Unused. |
References
Hedges, L. V., Tipton, E., and Johnson, M. C. (2010). Robust variance estimation in meta-regression with dependent effect size estimates. Research Synthesis Methods, 1(1), 39–65. doi:10.1002/jrsm.5.