| Title: | Robust Bayesian Meta-Analyses |
| Version: | 4.1.1 |
| Maintainer: | František Bartoš <f.bartos96@gmail.com> |
| Description: | A framework for Bayesian meta-analysis, including model estimation, prior specification, model comparison, prediction, summaries, visualizations, and diagnostics. The package fits single and model-averaged meta-analytic, meta-regression, multilevel and multivariate, publication bias adjusted, and generalized linear mixed models. The model-averaged meta-analytic models combine competing models based on their predictive performance, weight inference by posterior model probabilities, and test model components using Bayes factors (e.g., effect vs. no effect; Bartoš et al., 2022, <doi:10.1002/jrsm.1594>; Maier, Bartoš & Wagenmakers, 2022, <doi:10.1037/met0000405>; Bartoš et al., 2025, <doi:10.1037/met0000737>). Users can specify flexible prior distributions for effect sizes, heterogeneity, publication bias (including selection models and PET-PEESE), and moderators. |
| URL: | https://fbartos.github.io/RoBMA/ |
| BugReports: | https://github.com/FBartos/RoBMA/issues |
| License: | GPL-3 |
| Encoding: | UTF-8 |
| LazyData: | true |
| RoxygenNote: | 7.3.3 |
| SystemRequirements: | JAGS (>= 4.3.1, < 5.0.0) (https://mcmc-jags.sourceforge.io/) |
| NeedsCompilation: | yes |
| Depends: | R (≥ 4.3.0) |
| Imports: | BayesTools (≥ 0.4.0), bridgesampling, loo (≥ 2.10.0), MASS, Matrix (≥ 1.6-2), parallel, ps, runjags, rjags, statmod, stats, graphics, mvtnorm, scales, Rdpack, rlang, coda, ggplot2 |
| Suggests: | metafor (≥ 5.0-1), posterior, weightr, lme4, fixest, metaBMA, emmeans, metadat, testthat (≥ 3.3.2), R6, withr, cli, vdiffr, knitr, rmarkdown, covr, pkgload, processx |
| LinkingTo: | Matrix (≥ 1.6-2), mvtnorm |
| RdMacros: | Rdpack |
| VignetteBuilder: | knitr |
| Packaged: | 2026-11-08 15:18:09 UTC; fbart |
| Author: | František Bartoš |
| Repository: | CRAN |
| Date/Publication: | 2026-11-08 18:40:02 UTC |
RoBMA: Robust Bayesian Meta-Analysis
Description
RoBMA provides Bayesian meta-analysis, meta-regression, multilevel
meta-analysis, model averaging, and publication-bias adjustment. The main
user-facing fitters are RoBMA, RoBMA.mv,
BMA, BMA.mv, brma,
brma.mv, brma.glmm,
bselmodel, bselmodel.mv, bPET,
bPEESE, bPET.mv, and
bPEESE.mv.
User guide
See Bartoš et al. (2023),
Maier et al. (2023),
Bartoš et al. (2022), and
Bartoš et al. (2026) for the RoBMA methodology.
Use vignette(package = "RoBMA") to list installed vignettes.
Author(s)
Frantisek Bartos f.bartos96@gmail.com
References
Bartoš F, Maier M, Quintana DS, Wagenmakers E (2022).
“Adjusting for publication bias in JASP and R — Selection models, PET-PEESE, and robust Bayesian meta-analysis.”
Advances in Methods and Practices in Psychological Science, 5(3), 1–19.
doi:10.1177/25152459221109259.
Bartoš F, Maier M, Wagenmakers E (2026).
“Robust Bayesian multilevel meta-analysis: Adjusting for publication bias in the presence of dependent effect sizes.”
Behavior Research Methods.
doi:10.31234/osf.io/9tgp2_v2.
Preprint available at https://doi.org/10.31234/osf.io/9tgp2_v2.
Bartoš F, Maier M, Wagenmakers E, Doucouliagos H, Stanley TD (2023).
“Robust Bayesian meta-analysis: Model-averaging across complementary publication bias adjustment methods.”
Research Synthesis Methods, 14(1), 99–116.
doi:10.1002/jrsm.1594.
Maier M, Bartoš F, Wagenmakers E (2023).
“Robust Bayesian Meta-Analysis: Addressing publication bias with model-averaging.”
Psychological Methods, 28(1), 107–122.
doi:10.1037/met0000405.
See Also
Useful links:
Unsupported Information Criteria for brma Objects
Description
brma objects expose posterior pointwise log-likelihood draws
(logLik.brma, log_lik), not a maximized scalar
log-likelihood. AIC and BIC are therefore undefined and these methods always
stop with an explicit error.
Usage
## S3 method for class 'brma'
AIC(object, ..., k = 2)
## S3 method for class 'brma'
BIC(object, ...)
Arguments
object |
a brma model object. |
... |
ignored. |
k |
ignored; retained for the |
Value
These methods do not return a value.
See Also
log_lik, logLik.brma,
loo.brma, waic.brma
23 experimental studies from Anderson et al. (2010) that meet the best practice criteria
Description
The data set contains correlation coefficients, sample sizes, and labels for 23 experimental studies focusing on the effect of violent video games on aggressive behavior.
Usage
Anderson2010
Format
A data.frame with 3 columns and 23 observations:
rCorrelation coefficient.
nSample size.
nameStudy label.
Source
https://github.com/Joe-Hilgard/Anderson-meta
References
Anderson CA, Shibuya A, Ihori N, Swing EL, Bushman BJ, Sakamoto A, Rothstein HR, Saleem M (2010). “Violent video game effects on aggression, empathy, and prosocial behavior in Eastern and Western countries: A meta-analytic review.” Psychological Bulletin, 136(2), 151–173. doi:10.1037/a0018251.
39 study rows on household chaos and child executive functions from a meta-analysis by Andrews et al. (2021)
Description
The data set contains raw correlation coefficients and
sampling information using metafor-compatible column names
(ri, vi, sei, ni, and slab), together with
study-level moderators from the original data set. Three source rows have
missing effect-size inputs and are omitted automatically by model-fitting
functions that require complete outcomes. The original data set assessed the
effect of household chaos on child executive functions
(Andrews et al. 2021) and was used as an example in
Bartoš et al. (2025).
Usage
Andrews2021
Format
A data.frame with 15 columns and 39 observations:
study_idSource row identifier.
slabStudy label.
riRaw correlation coefficient.
viSampling variance of the raw correlation coefficient.
seiSampling standard error of the raw correlation coefficient.
niSample size.
yearPublication year.
percent_femalePercentage of female children in the sample.
ageMean age of the children in years.
assessment_interval_monthsTime between household-chaos and executive-function assessments in months.
dissertationWhether the study was a dissertation.
percent_minorityPercentage of minority participants in the sample.
percent_low_parental_educationPercentage of parents with high school, GED, or lower education.
hc_dimensionHousehold-chaos dimension using the source coding.
measureExecutive-function assessment type, direct or informant.
References
Andrews K, Atkinson L, Harris M, Gonzalez A (2021).
“Examining the effects of household chaos on child executive functions: A meta-analysis.”
Psychological Bulletin, 147(1), 16–32.
doi:10.1037/bul0000311.
Bartoš F, Maier M, Stanley TD, Wagenmakers E (2025).
“Robust Bayesian meta-regression: Model-averaged moderation analysis in the presence of publication bias.”
Psychological Methods.
doi:10.1037/met0000737.
Bayesian Model-Averaged Meta-Analysis
Description
Fits Bayesian model-averaged meta-analytic models without
publication-bias adjustment. BMA() is an alias for BMA.norm().
Usage
BMA(
yi,
vi,
sei,
weights,
ni,
mods,
scale,
cluster,
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_heterogeneity_allocation,
prior_effect_null,
prior_heterogeneity_null,
prior_mods_null,
prior_scale_null,
prior_heterogeneity_allocation_null,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "meandif",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent = TRUE,
...
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution(s) for the alternative effect component(s). |
prior_heterogeneity |
prior distribution(s) for the alternative heterogeneity component(s). |
prior_mods |
prior distribution(s) for alternative moderator
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_scale |
prior distribution(s) for alternative scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_heterogeneity_allocation |
prior distribution(s) for the
alternative cluster-level heterogeneity allocation component(s). This
argument can be specified only when |
prior_effect_null |
prior distribution(s) for the null effect component(s). |
prior_heterogeneity_null |
prior distribution(s) for the null heterogeneity component(s). |
prior_mods_null |
prior distribution(s) for null moderator components.
A named |
prior_scale_null |
prior distribution(s) for null scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_heterogeneity_allocation_null |
prior distribution(s) for the
null cluster-level heterogeneity allocation component(s). This argument can
be specified only when |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
Details
BMA.norm (and its alias BMA) provides a simplified interface for
Bayesian model-averaged meta-analysis when publication bias adjustment is not needed.
It uses the same product-space mixture-prior machinery as RoBMA() but
omits selection models and PET-PEESE bias adjustment.
For publication bias adjusted meta-analysis, use RoBMA directly.
Value
A fitted object of class c("BMA.norm", "RoBMA", "brma").
The object contains checked data, checked mixture priors, the JAGS
fit, cached summary, and cached coefficients.
See Also
RoBMA() brma() summary.brma() plot.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- BMA(
yi = yi,
vi = vi,
mods = ~ Preregistered,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
summary(fit)
}
## End(Not run)
Bayesian Model-Averaged Generalized Meta-Analysis
Description
Function for fitting Bayesian model-averaged meta-analytic models
directly to binary or count data using a generalized linear mixed model (GLMM)
framework. Unlike RoBMA, this function does not adjust for
publication bias, as weight function and regression-based bias adjustment
methods are not available for GLMM outcomes.
Usage
BMA.glmm(
ai,
bi,
ci,
di,
n1i,
n2i,
x1i,
x2i,
t1i,
t2i,
weights,
mods,
scale,
cluster,
data,
slab,
subset,
measure = "OR",
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_heterogeneity_allocation,
prior_baserate,
prior_lograte,
prior_effect_null,
prior_heterogeneity_null,
prior_mods_null,
prior_scale_null,
prior_heterogeneity_allocation_null,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "meandif",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent = TRUE,
...
)
Arguments
ai |
a vector of the number of events in the treatment or experimental group for binomial GLMM models. |
bi |
a vector of the number of non-events in the treatment or experimental group for binomial GLMM models. |
ci |
a vector of the number of events in the control group for binomial GLMM models. |
di |
a vector of the number of non-events in the control group for binomial GLMM models. |
n1i |
a vector of the sample size in the treatment or experimental
group. If omitted for binomial GLMMs, it is computed as |
n2i |
a vector of the sample size in the control group. If omitted for
binomial GLMMs, it is computed as |
x1i |
a vector of the number of events in the treatment/experimental group (for Poisson data). |
x2i |
a vector of the number of events in the control group (for Poisson data). |
t1i |
a vector of the person-time in the treatment/experimental group. |
t2i |
a vector of the person-time in the control group. |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution(s) for the alternative effect component(s). |
prior_heterogeneity |
prior distribution(s) for the alternative heterogeneity component(s). |
prior_mods |
prior distribution(s) for alternative moderator
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_scale |
prior distribution(s) for alternative scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_heterogeneity_allocation |
prior distribution(s) for the
alternative cluster-level heterogeneity allocation component(s). This
argument can be specified only when |
prior_baserate |
prior distribution for the estimate-specific midpoint
base-rate probability in binomial GLMM models ( |
prior_lograte |
prior distribution for the estimate-specific midpoint
log-rate in Poisson GLMM models ( |
prior_effect_null |
prior distribution(s) for the null effect component(s). |
prior_heterogeneity_null |
prior distribution(s) for the null heterogeneity component(s). |
prior_mods_null |
prior distribution(s) for null moderator components.
A named |
prior_scale_null |
prior distribution(s) for null scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_heterogeneity_allocation_null |
prior distribution(s) for the
null cluster-level heterogeneity allocation component(s). This argument can
be specified only when |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
Details
BMA.glmm combines the data input style of brma.glmm with
the mixture prior specification of RoBMA for Bayesian model-averaging.
Model for odds ratios (measure = "OR") uses a binomial-normal model
as described in Jackson et al. (2018).
Model for incidence rate ratios (measure = "IRR") uses a Poisson-normal
model as described in Bagos and Nikolopoulos (2009).
When weights are supplied, they are treated as likelihood weights on
the paired two-arm study contribution.
For factor moderators, BMA.glmm() defaults to
set_contrast_factor_predictors = "meandif", matching the other
model-averaging constructors. This differs from brma.glmm(),
which defaults to "treatment" as a single-model constructor.
Value
A fitted object of class
c("BMA.glmm", "RoBMA", "brma.glmm", "brma"). The object contains checked
data, checked mixture priors, the JAGS fit, cached summary, and
cached coefficients.
See Also
brma.glmm() RoBMA() summary.brma() plot.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
fit <- BMA.glmm(
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg,
measure = "OR",
seed = 1,
silent = TRUE
)
summary(fit)
}
## End(Not run)
Bayesian Model-Averaged Multivariate Meta-Analysis
Description
Fits Bayesian model-averaged multivariate and multilevel
meta-analytic models with known sampling covariance and formula random
effects. Random structures supplied through random are model-averaged with
independent component gates.
Usage
BMA.mv(
yi,
V,
ni,
mods,
scale,
random,
R = NULL,
Rscale = "cor",
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_effect_null,
prior_heterogeneity_null,
prior_mods_null,
prior_scale_null,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "meandif",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
known_v_parameterization = "auto",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent = TRUE,
...,
vi = NULL,
sei = NULL
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
V |
a known working variance-covariance matrix, a list of block
variance-covariance matrices, or an exact diagonal-plus-factor declaration
created by |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
random |
Optional BayesTools random-effect formula or list of formulas.
Omission or |
R |
optional known random-effect group covariance/correlation matrix,
or a named list of matrices. Matrix row and column names identify grouping
levels. This is distinct from the known sampling covariance |
Rscale |
scaling applied to each supplied |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution(s) for the alternative effect component(s). |
prior_heterogeneity |
prior distribution(s) for the alternative heterogeneity component(s). |
prior_mods |
prior distribution(s) for alternative moderator
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_scale |
prior distribution(s) for alternative scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_effect_null |
prior distribution(s) for the null effect component(s). |
prior_heterogeneity_null |
prior distribution(s) for the null heterogeneity component(s). |
prior_mods_null |
prior distribution(s) for null moderator components.
A named |
prior_scale_null |
prior distribution(s) for null scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
known_v_parameterization |
known- |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
Details
Omitted or NULL random specifies no heterogeneity and no random-effect
inclusion mixture. Heterogeneity priors and scale formulas require an
explicit random structure; the known sampling covariance remains unchanged.
BMA.mv() combines the product-space model-averaging workflow of BMA()
with the likelihood, formula, random-effect, and known-covariance machinery
of brma.mv(). For multiple top-level random components, a Dirichlet prior
allocates the slab total variance and an independent Bernoulli gate multiplies
each allocated contribution. The allocation is not renormalized when a gate
is off. Thus component j contributes
I_j w_j \tau^2,
where I_j is its inclusion indicator, w_j is its slab allocation,
and \tau is the slab total SD. With one component, no artificial
Dirichlet weight is created and the contribution is I_1 \tau^2.
By default, every top-level component has an independent 0.5 inclusion
probability. prior_heterogeneity defines the shared positive slab and
prior_heterogeneity_null defines exclusion at exactly zero. Their prior
weights determine the common gate probability; multiple alternative priors
retain their relative weights within the slab. Setting
prior_heterogeneity_null = NULL or FALSE fixes all component gates on,
while prior_heterogeneity = NULL or FALSE fixes them off. Nested random
terms are gated as one top-level component before their internal Dirichlet
split.
Component-specific or partial scale models instead have independent SD roots,
with allocation within each component; unscaled components keep their own
base SD prior. See random_effect_prior_specification.
A partial BayesTools::prior_random() supplied through
prior_heterogeneity may override contrasts, correlations, monitoring, and
parameterization. BMA.mv() owns the gated scale architecture, so a custom
prior_random() must not supply an SD, SD source, term-specific SD,
covariance-owned SD, or variance allocation.
Random-effect inclusion probabilities are reported separately from fixed
effect and scale-regression inclusion. Averaged random-component SDs retain
the excluded zero branch; conditional random summaries condition each
component on its own gate. tau_total and tau2_total are the realized gated
aggregate, including zero when every component is excluded. tau2_prop(j) is
the realized share I_j w_j / \sum_k I_k w_k, conditional on positive
total heterogeneity. Excluded components therefore have zero share, and the
all-off branch is omitted only from variance-proportion summaries. The
positive slab scale and raw Dirichlet weights remain internal coordinates.
Product-space marginal likelihood and bridge-sampling methods are not
available. Predictive comparison through loo.brma() and waic.brma()
remains available. If V is singular, every allowed product-space branch
must contain structural variance sufficient to regularize its null space;
an allowed all-components-off branch is therefore rejected.
The function does not add publication-bias models. Use RoBMA.mv() to add
model-averaged selection, PET, and PEESE publication-bias adjustments.
Value
A fitted object of class
c("BMA.mv", "RoBMA", "brma.mv", "brma.norm", "brma").
See Also
BMA(), RoBMA.mv(), brma.mv(), summary.brma(),
summary_models()
Examples
## Not run:
data("dat.assink2016", package = "metadat")
V <- metafor::vcalc(
vi,
cluster = study,
type = deltype,
obs = esid,
rho = c(0.7, 0.5),
data = dat.assink2016
)
fit <- BMA.mv(
yi = yi,
V = V,
mods = ~ deltype,
random = ~ 1 | study / esid,
data = dat.assink2016,
measure = "SMD",
seed = 1,
silent = TRUE
)
summary(fit)
summary_models(fit)
## End(Not run)
9 experimental studies from Bem (2011) as described in Bem et al. (2011)
Description
The data set contains Cohen's d effect sizes, standard errors, and labels for 9 experimental studies of precognition from the infamous Bem (2011) as analyzed in his later meta-analysis (Bem et al. 2011).
Usage
Bem2011
Format
A data.frame with 3 columns and 9 observations:
dCohen's d effect size.
seStandard error of d.
studyStudy label.
References
Bem DJ (2011).
“Feeling the future: Experimental evidence for anomalous retroactive influences on cognition and affect.”
Journal of Personality and Social Psychology, 100(3), 407–425.
doi:10.1037/a0021524.
Bem DJ, Utts J, Johnson WO (2011).
“Must psychologists change the way they analyze their data?”
Journal of Personality and Social Psychology, 101(4), 716–719.
doi:10.1037/a0024777.
1159 effect sizes from a meta-analysis of beauty and professional success by Havránková et al. (2025)
Description
The data set contains effect sizes (percent increase in earnings), standard errors, study identifiers, sample sizes, and the type of customer contact (no, some, or direct). The meta-analysis examined the relationship between perceived beauty and professional success (Havránková et al. 2025).
Usage
Havrankova2025
Format
A data.frame with 5 columns and 1159 observations:
yEffect size: percent increase in earnings.
seStandard error of y.
facing_customerType of customer contact.
study_idStudy identifier.
NSample size.
References
Havránková Z, Havránek T, Bortnikova K, Bartoš F (2025). “Meta-analysis of field studies on beauty and professional success.” Preprint available at https://meta-analysis.cz/beauty/beauty.pdf.
106 analyst-team effect-size estimates of the relation between religiosity and well-being from Hoogeveen et al. (2023)
Description
The data set contains standardized effect-size estimates, standard errors, 95% confidence interval bounds, sample sizes, effect-size types, sequential analyst-team identifiers, and team-level characteristics describing psychological dependent-variable coding and self-reported methodological knowledge. The Many-Analysts Religion Project examined whether religious people self-report greater well-being (Hoogeveen et al. 2023).
Usage
Hoogeveen2023
Format
A data.frame with 9 columns and 106 observations:
yiStandardized effect-size estimate.
seiStandard error of the effect-size estimate.
lciLower bound of the reported 95% confidence interval.
uciUpper bound of the reported 95% confidence interval.
niAnalysis sample size.
typeReported effect-size type: standardized regression coefficient beta or Cohen's d.
teamSequential analyst-team identifier in this example.
team_psychWhether the effect estimate used the psychological dependent-variable coding.
team_knowledgeTeam's self-reported methodological-knowledge rating, from 1 (no knowledge) to 5 (expert).
Source
References
Hoogeveen S, Sarafoglou A, Aczel B, Aditya Y, Alayan AJ, others (2023). “A many-analysts approach to the relation between religiosity and well-being.” Religion, Brain & Behavior, 13(3), 237–283. doi:10.1080/2153599X.2022.2070255.
37 studies from a meta-analysis of social comparison as a behavior change technique by Hoppen et al. (2025)
Description
The data set contains Cohen's d effect sizes, variances, and study characteristics including outcome type, feedback level, social comparison type, number of sessions, sample type, sample size, and country. The meta-analysis examined social comparison as a behavior change technique across the behavioral sciences (Hoppen et al. 2025).
Usage
Hoppen2025
Format
A data.frame with 9 columns and 37 observations:
dCohen's d effect size.
vSampling variance of d.
outcomeOutcome type.
feedback_levelFeedback level.
social_comparison_typeSocial-comparison type.
sessionsNumber of sessions.
sample_typeSample type.
sample_sizeSample size.
countryCountry.
References
Hoppen TH, Cuno RM, Nelson J, Lemmel F, Schlechter P, Morina N (2025). “Meta-analysis of randomized controlled trials examining social comparison as a behaviour change technique across the behavioural sciences.” Nature Human Behaviour, 9(8), 1595–1612. doi:10.1038/s41562-025-02209-2.
412 effect sizes from a meta-analysis of secondary benefits of family-based treatments by Johnides et al. (2025)
Description
The data set contains Cohen's d effect sizes, standard errors, and study labels from a meta-analysis investigating the extent to which family-based treatments for children with mental health, physical health, and developmental disorders provide secondary benefits to the children's siblings and caregivers (Johnides et al. 2025).
Usage
Johnides2025
Format
A data.frame with 3 columns and 412 observations:
studyStudy label.
dCohen's d effect size.
seStandard error of d.
References
Johnides BD, Borduin CM, Sheerin KM, Kuppens S (2025). “Secondary benefits of family member participation in treatments for childhood disorders: A multilevel meta-analytic review.” Psychological Bulletin, 151(1), 1–32. doi:10.1037/bul0000462.
881 estimates from 69 studies of a relationship between employment and educational outcomes collected by Kroupova et al. (2024)
Description
The data set contains partial correlation coefficients, standard errors, study labels, sample sizes, type of the educational outcome, intensity of the employment, gender of the student population, study location, study design, whether the study controlled for endogeneity, and whether the study controlled for motivation. The original data set including additional variables and the publication are available from the project page. (Note that some standard errors and employment intensities are missing.)
Usage
Kroupova2021
Format
A data.frame with 11 columns and 881 observations:
rPartial correlation coefficient.
seStandard error of r.
studyStudy label.
sample_sizeSample size.
education_outcomeType of educational outcome.
employment_intensityEmployment intensity.
students_genderGender composition of the student sample.
locationStudy location.
designStudy design.
endogenity_controlWhether endogeneity was controlled.
motivation_controlWhether motivation was controlled.
Source
https://meta-analysis.cz/students/
References
Kroupova K, Havranek T, Irsova Z (2024). “Student employment and education: A meta-analysis.” Economics of Education Review, 100, 102539. doi:10.1016/j.econedurev.2024.102539.
18 studies of a relationship between acculturation mismatch and intergenerational cultural conflict collected by Lui (2015)
Description
The data set contains correlation coefficients r, sample sizes n, and labels for each study assessing the relationship between acculturation mismatch (that is the result of the contrast between the collectivist cultures of Asian and Latin immigrant groups and the individualist culture in the United States) and intergenerational cultural conflict (Lui 2015) which was used as an example in Bartoš et al. (2022).
Usage
Lui2015
Format
A data.frame with 3 columns and 18 observations:
rCorrelation coefficient.
nSample size.
studyStudy label.
References
Bartoš F, Maier M, Quintana DS, Wagenmakers E (2022).
“Adjusting for publication bias in JASP and R — Selection models, PET-PEESE, and robust Bayesian meta-analysis.”
Advances in Methods and Practices in Psychological Science, 5(3), 1–19.
doi:10.1177/25152459221109259.
Lui PP (2015).
“Intergenerational cultural conflict, mental health, and educational outcomes among Asian and Latino/a Americans: Qualitative and meta-analytic review.”
Psychological Bulletin, 141(2), 404–446.
doi:10.1037/a0038449.
55 effect sizes from Many Labs 2 replication studies of Tversky and Kahneman (1981) framing effects
Description
The data set contains standardized mean differences (y) and standard errors (se) from 55 replication studies of the framing effect originally described by Tversky and Kahneman (1981). These studies were part of the Many Labs 2 project examining variation in replicability across samples and settings Klein et al. (2018).
Usage
ManyLabs16
Format
A data.frame with 2 columns and 55 observations:
yStandardized mean difference.
seStandard error of y.
References
Klein RA, Vianello M, Hasselman F, Adams BG, Adams Jr RB, Alper S, Aveyard M, Axt JR, Babalola MT, Bahník Š, others (2018).
“Many Labs 2: Investigating variation in replicability across samples and settings.”
Advances in Methods and Practices in Psychological Science, 1(4), 443–490.
doi:10.1177/2515245918810225.
Tversky A, Kahneman D (1981).
“The framing of decisions and the psychology of choice.”
Science, 211(4481), 453–458.
doi:10.1126/science.7455683.
5 studies with a tactile outcome assessment from Poulsen et al. (2006) of the effect of potassium-containing toothpaste on dentine hypersensitivity
Description
The data set contains Cohen's d effect sizes, standard errors, and labels for 5 studies assessing the tactile outcome from a meta-analysis of the effect of potassium-containing toothpaste on dentine hypersensitivity (Poulsen et al. 2006) which was used as an example in Bartoš et al. (2021).
Usage
Poulsen2006
Format
A data.frame with 3 columns and 5 observations:
dCohen's d effect size.
seStandard error of d.
studyStudy label.
References
Bartoš F, Gronau QF, Timmers B, Otte WM, Ly A, Wagenmakers E (2021).
“Bayesian model-averaged meta-analysis in medicine.”
Statistics in Medicine, 40(30), 6743–6761.
doi:10.1002/sim.9170.
Poulsen S, Errboe M, Mevil YL, Glenny A (2006).
“Potassium containing toothpastes for dentine hypersensitivity.”
Cochrane Database of Systematic Reviews.
doi:10.1002/14651858.cd001476.pub2.
Robust Bayesian Model-Averaged Meta-Analysis
Description
Fits a robust Bayesian model-averaged meta-analysis. The default ensemble averages across models with and without an effect, heterogeneity, and publication-bias adjustment.
Usage
RoBMA(
yi,
vi,
sei,
weights,
ni,
mods,
scale,
cluster,
data,
slab,
subset,
measure,
effect_direction = "detect",
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_heterogeneity_allocation,
prior_bias,
prior_effect_null,
prior_heterogeneity_null,
prior_mods_null,
prior_scale_null,
prior_heterogeneity_allocation_null,
prior_bias_null,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "meandif",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
model_type = "PSMA",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent = TRUE,
selection = BayesTools::selection_model(),
selection_control = set_selection_likelihood_control(),
...
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
effect_direction |
direction used by publication-bias adjustments.
|
prior_effect |
prior distribution(s) for the alternative effect component(s). |
prior_heterogeneity |
prior distribution(s) for the alternative heterogeneity component(s). |
prior_mods |
prior distribution(s) for alternative moderator
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_scale |
prior distribution(s) for alternative scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_heterogeneity_allocation |
prior distribution(s) for the
alternative cluster-level heterogeneity allocation component(s). This
argument can be specified only when |
prior_bias |
prior distribution(s) for alternative publication-bias component(s), such as weight functions, PET, or PEESE. Alternative prior arguments can be:
See |
prior_effect_null |
prior distribution(s) for the null effect component(s). |
prior_heterogeneity_null |
prior distribution(s) for the null heterogeneity component(s). |
prior_mods_null |
prior distribution(s) for null moderator components.
A named |
prior_scale_null |
prior distribution(s) for null scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_heterogeneity_allocation_null |
prior distribution(s) for the
null cluster-level heterogeneity allocation component(s). This argument can
be specified only when |
prior_bias_null |
prior distribution(s) for null publication-bias
component(s), usually Null prior arguments can be:
Defaults to a point mass (spike) at zero for effect and heterogeneity parameters. |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
model_type |
character string specifying predefined publication-bias model ensembles. One of:
Custom |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
selection |
specification created by |
selection_control |
numerical integration settings created by
|
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
Details
RoBMA() uses product-space Bayesian model averaging. Inclusion Bayes
factors and model-averaged estimates are obtained from mixture priors for
effect, heterogeneity, moderators, scale regression, and publication-bias
components.
By default, model_type = "PSMA" includes selection-model weight functions
together with PET and PEESE publication-bias adjustments. Use BMA() for
model averaging without publication-bias adjustment, or brma() for fitting
a single meta-analytic model.
RoBMA() uses normal/effect-size input (yi with vi or sei). Raw-count
GLMM model averaging is provided by BMA.glmm().
selection configures every generated default weightfunction. Its default
integrates estimate-level random effects and the complete sampling error,
and conditions on other random effects. Explicit priors retain their nested
selection_model() settings. Active selection branches must share the same
conditioning choices. Only weight_rule = "best" branches require and must
share a publication partition. Product branches ignore group; an ensemble
without "best" needs no publication groups and accepts group = NULL.
Branches can differ in weight-height priors, bins, and weight_rule.
These fixed model choices do not introduce new inclusion parameters.
Product-space objects support predictive comparison with add_loo() and
add_waic(). Bridge-sampling marginal likelihood via add_marglik() is
not available for product-space model-averaging objects.
Value
A fitted object of class c("RoBMA", "brma"). The object contains
checked data, checked priors, the JAGS fit, cached summary, and
cached coefficients. It can be passed to summary(), plot(),
predict(), funnel(), add_loo(), and related methods.
See Also
publication_bias_prior_specification, RoBMA.mv(), BMA(),
brma(), bselmodel(), bPET(), bPEESE(), summary.brma(), plot.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- RoBMA(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
summary(fit)
plot(fit)
}
## End(Not run)
Robust Bayesian Model-Averaged Multivariate Meta-Analysis
Description
Fits robust Bayesian model-averaged multivariate and multilevel meta-analytic models with known sampling covariance and formula random effects.
Usage
RoBMA.mv(
yi,
V,
ni,
mods,
scale,
random,
R = NULL,
Rscale = "cor",
data,
slab,
subset,
measure,
effect_direction = "detect",
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_bias,
prior_effect_null,
prior_heterogeneity_null,
prior_mods_null,
prior_scale_null,
prior_bias_null,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "meandif",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
model_type = "PSMA",
selection = BayesTools::selection_model(),
selection_control = set_selection_likelihood_control(),
known_v_parameterization = "auto",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent = TRUE,
...,
vi = NULL,
sei = NULL
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
V |
a known working variance-covariance matrix, a list of block
variance-covariance matrices, or an exact diagonal-plus-factor declaration
created by |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
random |
Optional BayesTools random-effect formula or list of formulas.
Omission or |
R |
optional known random-effect group covariance/correlation matrix,
or a named list of matrices. Matrix row and column names identify grouping
levels. This is distinct from the known sampling covariance |
Rscale |
scaling applied to each supplied |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
effect_direction |
direction used by publication-bias adjustments.
|
prior_effect |
prior distribution(s) for the alternative effect component(s). |
prior_heterogeneity |
prior distribution(s) for the alternative heterogeneity component(s). |
prior_mods |
prior distribution(s) for alternative moderator
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_scale |
prior distribution(s) for alternative scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_bias |
prior distribution(s) for alternative publication-bias component(s), such as weight functions, PET, or PEESE. Alternative prior arguments can be:
See |
prior_effect_null |
prior distribution(s) for the null effect component(s). |
prior_heterogeneity_null |
prior distribution(s) for the null heterogeneity component(s). |
prior_mods_null |
prior distribution(s) for null moderator components.
A named |
prior_scale_null |
prior distribution(s) for null scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_bias_null |
prior distribution(s) for null publication-bias
component(s), usually Null prior arguments can be:
Defaults to a point mass (spike) at zero for effect and heterogeneity parameters. |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
model_type |
character string specifying predefined publication-bias model ensembles. One of:
Custom |
selection |
specification created by |
selection_control |
numerical integration settings created by
|
known_v_parameterization |
known- |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
Details
Omitted or NULL random specifies no heterogeneity or random-effect
inclusion mixture. Publication-bias and fixed-effect alternatives remain
available. Heterogeneity priors and scale formulas require an explicit
random structure; the known sampling covariance remains unchanged.
RoBMA.mv() combines the publication-bias product space of RoBMA() with
the known-covariance, formula, random-effect, and prediction machinery of
brma.mv(). Selection models, PET, PEESE, and the unadjusted branch are
averaged together according to model_type or custom prior_bias and
prior_bias_null specifications. Selection is defined over the estimates
in each publication event. PET uses sqrt(diag(V)) and PEESE uses diag(V) as their
bias predictors while the likelihood retains the full known sampling
covariance.
Random structures supplied through random use the same independent
component gates as BMA.mv(). A Dirichlet prior allocates the slab total
variance across multiple top-level components and each allocation is
multiplied by its own inclusion indicator without renormalizing the
remaining allocations.
Component-specific or partial scale models instead have independent SD roots,
with allocation within each component; unscaled components keep their own
base SD prior. See random_effect_prior_specification.
The default prior inclusion probability is 0.5 for
every component. Public tau_total and tau2_total draws are the realized
gated aggregate, including the all-off zero branch. Public
tau2_prop(...) draws are realized shares conditional on positive total
heterogeneity; excluded components have zero share, and the all-off branch
is undefined. The positive slab scale and raw Dirichlet weights remain
internal coordinates.
The constructor's selection specification applies to every generated
weightfunction. It integrates estimate-level random effects and the complete
sampling error by default, and conditions on other random effects.
Default product weights require no publication groups: group = NULL is
valid, including with a multilevel random formula and correlated V.
Explicit priors carry their own selection_model() settings. Active selection
branches must share one conditioning cell; only weight_rule = "best"
branches require and must share a publication partition. Product branches
ignore group. Their bins, weight priors, and weighting rules may differ.
Non-selection branches retain the corresponding Gaussian, PET, or PEESE
contribution with the same contextual source representation.
Whole sampling-error selection, grouping, and the Gaussian source
likelihood follow bselmodel.mv(). Numerical backends do not change these
model choices. All three source choices are explicit in selection.
Without an active selection branch, supported estimate-level Gaussian
random intercepts are automatically integrated into the likelihood variance.
Product-space marginal likelihood and bridge-sampling methods are not
available. Predictive comparison through loo.brma() and waic.brma()
remains available. If V is singular, every allowed product-space branch
must contain structural variance sufficient to regularize its null space.
Value
A fitted object of class
c("RoBMA.mv", "RoBMA", "brma.mv", "brma.norm", "brma").
See Also
RoBMA(), BMA.mv(), brma.mv(), bselmodel.mv(), bPET.mv(),
bPEESE.mv(), set_selection_likelihood_control(), summary.brma(),
summary_models()
Examples
## Not run:
data("dat.assink2016", package = "metadat")
V <- metafor::vcalc(
vi,
cluster = study,
type = deltype,
obs = esid,
rho = c(0.7, 0.5),
data = dat.assink2016
)
fit <- RoBMA.mv(
yi = yi,
V = V,
mods = ~ deltype,
random = ~ 1 | study / esid,
data = dat.assink2016,
measure = "SMD",
seed = 1,
silent = TRUE
)
summary(fit)
summary_models(fit)
## End(Not run)
Control MCMC fitting process
Description
set_autofit_control and set_convergence_checks control settings for the
autofit process of the MCMC JAGS sampler and specify termination criteria and convergence checks.
Usage
set_autofit_control(
max_Rhat = 1.05,
min_ESS = 500,
max_error = NULL,
max_SD_error = NULL,
max_time = list(time = 60, unit = "mins"),
sample_extend = 1000,
restarts = 10,
max_extend = 10,
check_indicators = FALSE,
monitor = NULL,
allow_not_assessable = FALSE
)
set_convergence_checks(
max_Rhat = 1.05,
min_ESS = 500,
max_error = NULL,
max_SD_error = NULL,
check_indicators = FALSE,
monitor = NULL,
allow_not_assessable = FALSE
)
Arguments
max_Rhat |
maximum value of the R-hat diagnostic.
Defaults to |
min_ESS |
minimum estimated sample size.
Defaults to |
max_error |
maximum value of the MCMC error.
Defaults to |
max_SD_error |
maximum value of the proportion of MCMC error
of the estimated SD of the parameter.
Defaults to |
max_time |
list with the time and unit specifying the maximum
autofitting process per model. Passed to difftime function
(possible units are |
sample_extend |
number of samples to extend the fitting process if
the criteria are not satisfied.
Defaults to |
restarts |
number of times new initial values should be generated in case a
model fails to initialize. Defaults to |
max_extend |
number of times after which the automatic fitting function is stopped.
Defaults to |
check_indicators |
whether model indicator variables should be included
in convergence checks. Binary indicators are checked as state occupancies
and categorical indicators are checked separately for every observed state.
Eligible indicators remain included when |
monitor |
optional character vector selecting the parameters used for
convergence checks. A base name selects all indexed elements. Defaults to
|
allow_not_assessable |
whether requested sampled parameters with
undefined diagnostics may be ignored. Defaults to |
Details
set_autofit_control controls the automatic model fitting process, determining when to
stop iterating based on convergence criteria. set_convergence_checks sets thresholds
for determining whether a model has converged adequately.
The autofit control manages computational resources by setting maximum time limits and
determining how many additional samples to draw if convergence criteria are not met.
The convergence checks determine the quality standards that fitted models must meet.
Autofit thresholds max_Rhat, min_ESS, max_error,
max_SD_error, max_time, restarts, and
max_extend can be set to NULL; sample_extend must be a
positive integer. The routing controls are delegated to
BayesTools::JAGS_check_convergence().
Thresholds can be disabled with NULL; otherwise max_Rhat must be
at least 1, min_ESS and max_error must be nonnegative, and
max_SD_error must be between 0 and 1.
Value
set_autofit_control returns a list of autofit control settings
including max_Rhat, min_ESS, max_error,
max_SD_error, max_time, sample_extend,
restarts, max_extend, check_indicators,
monitor, and allow_not_assessable.
set_convergence_checks returns a list with convergence thresholds
max_Rhat, min_ESS, max_error, max_SD_error,
check_indicators, monitor, and
allow_not_assessable.
See Also
Examples
# Set custom autofit control with shorter time limit
autofit_ctrl <- set_autofit_control(
max_time = list(time = 30, unit = "mins"),
sample_extend = 2000
)
# Set custom convergence checks with stricter criteria
conv_checks <- set_convergence_checks(
max_Rhat = 1.01,
min_ESS = 1000
)
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- RoBMA(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
autofit_control = autofit_ctrl,
convergence_checks = conv_checks
)
}
## End(Not run)
Options for the RoBMA package
Description
Inspect or change package-level defaults used by RoBMA.
Usage
RoBMA.options(...)
RoBMA.get_option(name)
Arguments
... |
named option(s) to change. Names must be exact public option names, nonempty, and unique. |
name |
a single non-missing character string matching one public option exactly; for available options, see details below. |
Details
The available options are:
max_coresnumber of cores to use for parallel computing (default is one fewer than detected logical cores, with a minimum/fallback of 1)
native_threadsmaximum number of native threads used to evaluate independent posterior rows of the compiled selection-likelihood batches in post-processing such as likelihood-aware densities, z-plots, and predictions. The default
NAinherits the model's fitting setup: models fitted withparallel = TRUEevaluate their post-processing rows with up tomax_coresnative threads, unless this option sets an explicit thread count. Parallel work is arranged so that every reduction sums in a fixed order, so results do not depend on the thread count; single-state fitting and bridge-sampling evaluations stay serial. A model fitted withparallel = FALSEdoes its post-processing serially unless this option sets an explicit thread count.check_scalingwhether to check scaling of predictors (default
TRUE)silentwhether to suppress JAGS output when fitting or extending models (default
FALSE); the model-averaging constructorsRoBMA(),BMA(),BMA.norm(),BMA.glmm(),RoBMA.mv(), andBMA.mv()default tosilent = TRUEand ignore the optionjags.worker_outputfile path for parallel JAGS worker stdout and stderr when fitting or extending. The parent directory must exist; workers append to the same file and messages may interleave. The default empty string disables capture. Set this option inside any background job that fits the model. It does not change sampling or numerical integration settings.
autocompute.loowhether to automatically compute LOO (default
FALSE); a GLMM whose nuisance-prior likelihood the quadrature cannot certify warns and the fit is returned without itautocompute.waicwhether to automatically compute WAIC (default
FALSE); a GLMM whose nuisance-prior likelihood the quadrature cannot certify warns and the fit is returned without itautocompute.marglikwhether to automatically compute marginal likelihood (default
FALSE)cluster_likelihood.n_gammanumber of Gauss-Hermite nodes formerly used for weighted normal cluster-unit log-likelihoods (default
15). Normal cluster-unit log-likelihoods, weighted or not, are now integrated in closed form, so the option is still accepted but no longer affects them; selected-normal likelihoods use their own quadrature schedules and integration controls.selection.cache_max_bytesone shared storage budget for exact and coarse selection-normalizer caches across all chains in a fit. The default
"auto"uses the smaller of 4 GiB and one quarter of currently available system RAM, resolved before fitting. Supply a nonnegative whole number of bytes to set an explicit total;0disables caching. Storage grows as needed. Chains receive equal shares, pooled within each worker process; sequential chains share the total.selection.cache_retainwhether to save selection-normalizer cache entries with the fitted object after fitting or extending (default
FALSE). Retained entries survivesaveRDS()and are restored when extending a compatible fit. Seeremove_selection_cachefor memory costs and removal.selection.sampler"default"retains ordinary JAGS sampling."coarse_corrected"uses coarse slice proposals with a full-target Metropolis correction for eligible scalar updates involving multivariate, cluster or factor step selection blocks (seeselection_sampler_infofor the blocks that take part). The posterior target is unchanged. Settings are captured when each model is compiled.selection.coarse_gridnamed nonnegative grid steps
c(mean = .05, variance = .05, log_weight = .01)of the dense multivariate step blocks; cluster and factor blocks evaluate their coarse rule at the actual parameters and ignore the grid. Mean spacing is its step times the largest original sampling SE in the block; covariance-diagonal spacing is its step times that SE squared. Each diagonal is rounded upward on a grid whose origin is its own squared original sampling SE, retaining all off-diagonal entries. Positive weights are rounded on the natural-log scale; zero weights remain zero. A zero step retains that coordinate exactly but does not disable the coarse rule budget or fallback. These settings affect proposals, not the corrected target.selection.coarse_max_rulescoarse quadrature rule budget (default
3, minimum3). Dense multivariate blocks try at most this many rules from the beginning of the fitted quadrature schedule for a coarse anchor; unsupported or unsuccessful coarse integration uses the prescribed unit normalizer, without QMC fallback. Cluster and factor blocks use the one rule of this number in their own schedule (the last rule of a shorter schedule) at the actual parameters, and the exact density where that rule is unavailable. The full-target evaluator retains its ordinary numerical controls and diagnostics.default_UISD.effectdefault scaling of the unit information standard deviation for the effect size parameter (default
0.5)default_UISD.heterogeneitydefault scaling of the unit information standard deviation for the heterogeneity parameter (default
0.25)default_UISD.modsdefault scaling of the unit information standard deviation for the moderators (default
0.25)default_UISD.scaledefault scaling of the unit information standard deviation for the scale parameter (default
0.5)default_lograte.sddefault standard deviation of the estimate-specific midpoint log-rate prior in Poisson GLMMs (default
1)default_informed_priors.modsdefault scaling of informed priors for moderators (default
0.5)default_informed_priors.scaledefault scaling of informed priors for the scale parameter (default
0.5)default_bias_weightfunction.alphadefault alpha for the weightfunction (default
1)default_bias_PET.scaledefault scale for the PET (default
1)default_bias_PEESE.scaledefault scale for the PEESE (default
5)
Boolean options require scalar TRUE or FALSE values.
max_cores must be integer-like and at least 1;
cluster_likelihood.n_gamma must be integer-like and at least 3.
native_threads accepts NA or a positive integer.
Scale and alpha defaults must be finite positive numbers.
Value
RoBMA.options() invisibly returns a named list with all current
options after applying any changes. RoBMA.get_option() returns the current
value of the requested option.
Prior specification for model-averaging
Description
The RoBMA and RoBMA.mv functions extend the
prior specification described in prior_specification by
allowing mixture priors that define competing hypotheses for Bayesian
model-averaging. This enables multimodel inference via the product space
method (Carlin and Chib 1995; Lodewyckx et al. 2011), where a
single MCMC chain explores a joint model space containing all competing
models.
Arguments
prior_effect |
prior distribution(s) for the alternative effect component(s). |
prior_heterogeneity |
prior distribution(s) for the alternative heterogeneity component(s). |
prior_mods |
prior distribution(s) for alternative moderator
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_scale |
prior distribution(s) for alternative scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_heterogeneity_allocation |
prior distribution(s) for the
alternative cluster-level heterogeneity allocation component(s). This
argument can be specified only when |
prior_bias |
prior distribution(s) for alternative publication-bias component(s), such as weight functions, PET, or PEESE. Alternative prior arguments can be:
See |
prior_effect_null |
prior distribution(s) for the null effect component(s). |
prior_heterogeneity_null |
prior distribution(s) for the null heterogeneity component(s). |
prior_mods_null |
prior distribution(s) for null moderator components.
A named |
prior_scale_null |
prior distribution(s) for null scale-regression
components. A single prior applies to all terms; a named list can specify
term-specific components. This argument can be specified only when |
prior_heterogeneity_allocation_null |
prior distribution(s) for the
null cluster-level heterogeneity allocation component(s). This argument can
be specified only when |
prior_bias_null |
prior distribution(s) for null publication-bias
component(s), usually Null prior arguments can be:
Defaults to a point mass (spike) at zero for effect and heterogeneity parameters. |
model_type |
character string specifying predefined publication-bias model ensembles. One of:
Custom |
Details
The product space method for model-averaging
RoBMA implements Bayesian model-averaging using the product space method (Carlin and Chib 1995; Lodewyckx et al. 2011). Rather than fitting each model separately and combining results after the fitting is complete, this approach embeds all competing models within a single joint model space. A discrete model indicator variable selects which model component is "active" at each MCMC iteration, and the posterior probability of each model is estimated from the proportion of iterations spent in that model's subspace.
This is achieved by specifying mixture priors that combine:
-
Null hypothesis component(s): Typically point masses (spikes) representing the absence of an effect, heterogeneity, or publication bias
-
Alternative hypothesis component(s): Continuous distributions representing the presence of the parameter
The mixture structure enables direct computation of:
-
Inclusion Bayes factors: Evidence for the presence vs. absence of each parameter (e.g., effect, heterogeneity, bias)
-
Model-averaged estimates: Posterior estimates that account for model uncertainty by weighting across all models
-
Conditional estimates: Posterior estimates given that a particular hypothesis is true
Default mixture prior structure
By default, RoBMA creates the following mixture priors:
| Parameter | Null component | Alternative component |
Effect (\mu) | Spike(0) | Normal(0, UISD-scaled) |
Heterogeneity (\tau) | Spike(0) | Normal+(0, UISD-scaled) |
| Publication bias | No bias (prior_none) | Weight functions + PET + PEESE |
Allocation (\rho) | (none by default) | Beta(1, 1) |
See prior_specification for details on how the UISD scaling is determined.
Specifying custom mixture priors
Single prior vs. list of priors
Each prior_* and prior_*_null argument accepts either a single prior or a list:
-
Single prior: Creates one component in the mixture
-
List of priors: Creates multiple components, enabling model-averaging across different prior specifications (e.g., different effect size scales)
When multiple priors are specified in a list, they are all treated as alternative (or null) hypothesis components for the main inclusion Bayes factor. The inclusion Bayes factor tests the combined evidence for all alternative components against all null components. The detailed summary output shows posterior probabilities and inclusion Bayes factors for each individual component separately, allowing finer-grained inference about which specific prior specification is most supported by the data.
Omitting hypothesis components
For top-level mixture components, setting a prior argument to NULL or FALSE
removes that hypothesis component:
-
prior_effect_null = NULL: No null hypothesis for effect (assumes effect exists) -
prior_effect = NULL: No alternative hypothesis (assumes no effect) -
prior_bias_null = NULLorFALSE: No "no bias" model (assumes some bias mechanism) -
prior_bias = NULLorFALSE: No bias model (assumes no bias mechanism)
For moderator and scale formula priors, an omitted or whole-argument
NULL uses the corresponding default. Whole-argument FALSE is not a
supported shortcut for omitting every term. Omit a particular alternative or
null component with a named NULL or FALSE entry, for example
prior_mods_null = list(x1 = NULL). Ordinary named terms replace only that
alternative or null component. A named alternative intercept instead
supplies the complete intercept prior, which must be a single simple or point
prior (for prior_scale, a single positive prior).
Null-list intercept declarations are refused, as are explicit global priors
discarded without a consumer. A global heterogeneity declaration can still
supply an unscaled root or component-inclusion weights when scale intercepts
have their own priors; retain it when it has such a consumer.
An ordered term's mixture belongs on its scalar total. Supply the complete
prior_ordered(total = ...) in one term component and omit the separate term
component with a named NULL entry. For example:
total <- BayesTools::prior_mixture(list(prior("point", list(0)),
prior("normal", list(0, 1))),
is_null = c(TRUE, FALSE))
BMA(yi = yi, sei = sei, mods = ~ f, data = dat, measure = "SMD",
prior_mods = list(f = prior_ordered(total = total)),
prior_mods_null = list(f = NULL), only_priors = TRUE)
Combining an ordered container with a separate term null or alternative is
unavailable and raises RoBMA_prior_error with the corresponding omission.
Parameter-specific customization for moderators
For moderator priors (prior_mods, prior_mods_null), you can specify different
priors for different predictors using named lists. A single prior object applies
to all moderator terms:
RoBMA(..., mods = ~ x1 + x2, prior_mods_null = list(x1 = NULL) # No null for x1, default null for x2 )
This allows testing whether specific moderators have effects while assuming others are always included or excluded.
Mixture priors for different parameter types
Effect size (\mu) and heterogeneity (\tau)
Effect and heterogeneity priors combine spike-and-slab components:
# Default: spike(0) null + normal alternative
# Custom: multiple alternatives with different scales
RoBMA(...,
prior_effect = list(
prior("normal", list(mean = 0, sd = 0.5)),
prior("normal", list(mean = 0, sd = 1.0))
)
)
Publication bias
Bias priors combine different publication bias adjustment mechanisms:
No publication bias (null hypothesis)
Weight functions: Selection models with different step functions
PET/PEESE: Regression-based bias adjustment
The model_type argument provides convenient presets:
RoBMA(..., model_type = "PSMA") # Full ensemble (default) RoBMA(..., model_type = "PP") # Only PET-PEESE models
See publication_bias_prior_specification for the bias-prior
constructors and preset model spaces.
Heterogeneity allocation (\rho) for multilevel models
When cluster is specified, \rho controls the cluster-level variance
allocation. The decomposition is
\tau_{between} = \tau\sqrt{\rho} and
\tau_{within} = \tau\sqrt{1 - \rho}. By default, only an alternative
(Beta(1,1)) is specified, but null hypotheses can be added:
RoBMA(...,
cluster = study,
prior_heterogeneity_allocation_null = prior("spike", list(location = 0.5))
)
Moderator and scale regression terms
When mods is specified, the effect prior becomes the intercept prior, and each
moderator receives a mixture prior. The intercept inherits the effect mixture
structure, while regression coefficients get separate spike-and-slab mixtures.
Similarly, when scale = ~ ... is specified for location-scale models, the
heterogeneity prior becomes the scale intercept prior, and each scale predictor
receives a mixture prior following the same pattern as moderator terms.
Note that the scale intercept (i.e., baseline heterogeneity) is always positive and
the multiplicative scale coefficients require non-zero prior distribution on the
intercept.
Model weights and prior odds
Each component in a mixture prior has an associated prior weight (prior model
probability). User-specified components receive equal weights unless their
prior objects set prior_weights. Publication-bias presets use fixed weights:
"2w" and "6w" split the alternative bias mass equally across their
weight functions, "PP" splits it equally across PET and PEESE, and "PSMA"
assigns half of the alternative bias mass to the six weight functions
combined and one quarter each to PET and PEESE. Custom weights can be
specified via the prior_weights argument in individual prior objects.
The prior odds between null and alternative hypotheses affect the Bayes factor interpretation. With equal prior weights on null and alternative, the posterior odds equal the Bayes factor.
References
Carlin BP, Chib S (1995).
“Bayesian model choice via Markov chain Monte Carlo methods.”
Journal of the Royal Statistical Society: Series B (Methodological), 57(3), 473–484.
doi:10.1111/j.2517-6161.1995.tb02042.x.
Lodewyckx T, Kim W, Lee MD, Tuerlinckx F, Kuppens P, Wagenmakers E (2011).
“A tutorial on Bayes factor estimation with the product space method.”
Journal of Mathematical Psychology, 55(5), 331–347.
doi:10.1016/j.jmp.2011.06.001.
See Also
prior_specification for base prior specification options,
publication_bias_prior_specification for publication-bias priors,
RoBMA and RoBMA.mv for the main model-averaging
functions,
prior for creating prior distribution objects
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
# Default mixture priors (spike-and-slab for effect and heterogeneity)
fit1 <- RoBMA(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
# Custom alternative priors (two effect size scales)
fit2 <- RoBMA(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
prior_effect = list(
prior("normal", list(mean = 0, sd = 0.35)),
prior("normal", list(mean = 0, sd = 0.70))
),
seed = 1,
silent = TRUE
)
# No null hypothesis for effect (assume effect exists)
fit3 <- RoBMA(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
prior_effect_null = NULL,
seed = 1,
silent = TRUE
)
# Only selection model bias adjustment (no PET-PEESE)
fit4 <- RoBMA(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
model_type = "6w",
seed = 1,
silent = TRUE
)
# Meta-regression with different null specifications per moderator
fit5 <- RoBMA(
yi = yi,
vi = vi,
mods = ~ Preregistered,
data = dat.lehmann2018,
measure = "SMD",
prior_mods_null = list(Preregistered = NULL),
seed = 1,
silent = TRUE
)
}
## End(Not run)
70 effect sizes from a meta-analysis of ChatGPT's impact on student learning by Wang and Fan (2025)
Description
The data set contains Hedges' g effect sizes, standard errors, sample sizes for experimental and control groups, and various study characteristics including grade level, type of course, duration, learning model, role of ChatGPT, and area of ChatGPT application. The meta-analysis examined the effect of ChatGPT on students' learning performance, learning perception, and higher-order thinking (Wang and Fan 2025).
Usage
Wang2025
Format
A data.frame with 12 columns and 70 observations:
Learning_effectLearning-effect outcome category.
Author_yearAuthor-year study label.
N_EGExperimental-group sample size.
N_CGControl-group sample size.
gHedges' g effect size.
Grade_levelGrade level.
Type_of_courseCourse type.
DurationStudy duration.
Learning_modelLearning model.
Role_of_ChatGPTRole of ChatGPT in the intervention.
Area_of_ChatGPT_applicationApplication area.
seStandard error of g.
References
Wang J, Fan W (2025). “The effect of ChatGPT on students’ learning performance, learning perception, and higher-order thinking: insights from a meta-analysis.” Humanities and Social Sciences Communications, 12(1), 1–21. doi:10.1057/s41599-025-04787-y.
582 effect sizes examining the ease-of-retrieval effect from a meta-analysis by Weingarten and Hutchinson (2018)
Description
The data set contains correlation coefficients between the manipulation and outcome variable (r_xy), sample sizes (N), and various study characteristics including publication status, country (USA vs. other), number of few and many examples requested, whether the trial targeted episodic memory, paradigm type (standard vs. other), dataset type (proximal vs. distal), and mediation variables (r_xm, r_my). The meta-analysis examined whether subjective ease mediates the ease-of-retrieval effect, where participants list either few or many examples and then make judgments (Weingarten and Hutchinson 2018).
Usage
Weingarten2018
Format
A data.frame with 12 columns and 582 observations:
r_xyCorrelation between manipulation and outcome.
NSample size.
paper_idPaper identifier.
publishedPublication-status indicator.
USAWhether the study was conducted in the USA.
number_of_fewNumber of examples in the few-examples condition.
number_of_manyNumber of examples in the many-examples condition.
episodic_memoryWhether the trial targeted episodic memory.
standard_paradigmWhether the standard paradigm was used.
proximal_datasetWhether the data set was proximal.
r_xmCorrelation between manipulation and mediator.
r_myCorrelation between mediator and outcome.
References
Weingarten E, Hutchinson JW (2018). “Does ease mediate the ease-of-retrieval effect? A meta-analysis.” Psychological Bulletin, 144(3), 227–283. doi:10.1037/bul0000122.
Add LOO-PSIS to brma Objects
Description
Compute approximate leave-one-out cross-validation (LOO-CV) using Pareto smoothed importance sampling (PSIS) for brma model objects and store the result in the object.
Usage
## S3 method for class 'brma'
add_loo(object, unit = "estimate", r_eff = NULL, parallel = FALSE, ...)
Arguments
object |
a brma model object. |
unit |
output/deletion unit. |
r_eff |
optional vector of relative effective sample sizes. If not provided, it is computed from the log-likelihood values. |
parallel |
Logical. If |
... |
additional arguments (currently ignored). |
Details
With unit = "estimate", LOO-CV is computed with one contribution per
effect-size estimate. For binomial and Poisson models, each pair of counts
(ai/ci or x1i/x2i) that defines a single effect size estimate is treated as
one contribution.
Estimate-unit GLMM log-likelihoods integrate the nuisance base rate or
log-rate over its prior: point priors and untruncated beta (base rate) and
normal (log-rate) priors adaptively, other priors on a refined prior-CDF
grid; a uniform(0, 1) base-rate prior is a Beta(1, 1) prior and is integrated
adaptively. The grid is accepted only when its log-likelihood changes by less
than 1e-6 between refinements. Any nuisance prior without an adaptive
route (other than an untruncated beta base rate or an untruncated normal
log-rate; truncated ones take the grid too) can fail to reach this,
especially with few events or very large arms, and then stops with an error of
class RoBMA_glmm_grid_nonconvergence (also of class
RoBMA_glmm_numerical_error); gamma, lognormal, and inverse-gamma
log-rate priors and lognormal base-rate priors are examples. A beta base-rate
prior or a normal log-rate prior avoids it. When the likelihood is computed
automatically after fitting (the autocompute.loo and
autocompute.waic options), such a failure gives a warning and the fit
is returned without LOO/WAIC; add_loo() then gives the same error.
With unit = "cluster", LOO-CV is computed with one joint contribution
per cluster. For normal models without selection, weighted or not, this uses
the closed-form Gaussian integral over the held-out cluster effect, with the
likelihood weights applied as powers of the row densities.
Cluster-unit binomial and Poisson GLMM log-likelihoods are unavailable until
certified nested adaptive quadrature is implemented; use
unit = "estimate" for GLMMs.
Cluster-unit contributions are also unavailable for brma.mv() models,
whose random-formula deletion semantics still need a dedicated design; use
unit = "estimate" there.
Selection-model deletion conditions the Gaussian law on retained outcomes and on the context declared by the fitted selection model. It preserves the original publication event and selection standard errors. Product weights on retained outcomes cancel; best selection continues to depend on the best p-value among both retained and deleted outcomes. This finite-vector deletion score differs from prediction for an entirely new publication event.
For Gaussian multilevel and known-V brma.mv() models,
estimate-unit LOO integrates Gaussian local effects and uses
p(y_i \mid y_{-i}, \theta) within each fitted dependency block. Thus
deleting one estimate retains the other estimates in its cluster or random-
effect block; it does not represent prediction for a wholly new group.
Gaussian brma(..., cluster = ...) models with non-unit likelihood
weights also integrate the cluster effect. Their score integrates the
entire powered row density against the cluster-effect distribution given
the retained weighted observations, including the power-dependent normalizing
constant. It is not the power of an unweighted marginal density. Earlier
stored weighted estimate-unit LOO results must be recomputed with
add_loo(); the fitted posterior does not need refitting for this
post-fit calculation. Selection and GLMM models retain their supported routes.
Numerically unresolved weighted Gaussian retained moments stop with
RoBMA_weighted_gaussian_unavailable, a
RoBMA_numerical_unavailable condition.
For brma.mv() models with known random-effect group covariance
R, the known R matrix and fitted random-effect covariance enter
the marginal ZGZ' covariance through BayesTools' compiled random-effect
metadata. The same calculation applies to every supported random structure.
Estimate-unit deletion retains the fitted grouping and known-V
dependency structure; it does not represent deletion of an entire new random
group. Models with no local effects, sampled local effects, marginalized
local effects, or a mixture of sampled and marginalized effects remain
comparable when their data hash, deletion unit, retained context, and
likelihood target agree. The sampled/marginalized labels are retained as
provenance rather than comparison keys.
The PSIS object is essential for model comparison via
loo_compare and is automatically saved in the loo result.
RoBMA stores target metadata so comparisons can reject mismatched data,
unit, or retained-context targets.
Each finite log-likelihood column observed to be constant across posterior
draws uses exact uniform importance ratios. Such columns bypass relative-ESS
and generalized-Pareto fitting, including when other columns vary. Their
Pareto-k diagnostic is recorded as the sentinel zero, meaning constant
ratios with no tail instability rather than an estimated Pareto shape.
Finite varying columns are centered by a column-specific constant before
relative-ESS and PSIS evaluation. The offset is restored exactly afterward,
preserving the LOO target while avoiding probability-scale underflow.
Important for model comparison: When comparing models via
loo_compare, the selection is based on expected
predictive performance for the documented deletion target, not in-sample
fit. For dependent estimates, deleting one estimate may retain other
observations from its fitted dependency block; this is not new-group
prediction.
Value
The brma object with the LOO result stored in
object[["loo"]][[unit]].
References
(Vehtari et al. 2017) (Vehtari et al. 2024)
See Also
loo.brma, loo,
loo_compare, pareto_k_ids
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_loo(fit)
loo_fit <- loo(fit)
print(loo_fit)
plot(loo_fit)
}
## End(Not run)
Add Marginal Likelihood to brma Objects
Description
Compute the marginal likelihood of a brma model using bridge sampling and store the result in the object.
Usage
## S3 method for class 'brma'
add_marglik(
object,
parallel = NULL,
cores = NULL,
repetitions = 1L,
method = c("normal", "warp3"),
maxiter = 10000L,
silent = TRUE,
...
)
Arguments
object |
a brma model object. |
parallel |
whether bridge-density evaluations run in parallel. The
default, |
cores |
number of bridge-sampling worker processes. The default,
|
repetitions |
number of independent bridge-sampling repetitions. |
method |
bridge transformation; either |
maxiter |
maximum number of bridge iterations per repetition. |
silent |
whether bridge-sampling progress is suppressed. The typed
iteration-limit diagnostic remains visible even when |
... |
reserved for future use. Unused arguments produce a warning. |
Details
The marginal likelihood is computed using the bridgesampling package
via the BayesTools::JAGS_bridgesampling wrapper. The result is stored
in the object and can be extracted using bridge_sampler.brma.
Proposal draws use the seed stored with the fit. When that seed is non-NULL,
the caller's random-number state is restored after the call; a NULL fit seed
uses and advances the caller's random-number stream.
A finite bridge estimate remains available when observed iteration counts
exceed maxiter. The stored result's success records finite
availability, not certified convergence. Its optional
iteration_limit_exceeded is TRUE for observed excess,
FALSE for complete counts without excess, and NA or absent
when telemetry is unavailable. Counts may include upstream retries.
Observed excess raises BayesTools_marglik_iteration_limit, inheriting
from BayesTools_marglik_diagnostic, under either silent setting.
Inspect print(object[["marglik"]]) and its repetition diagnostics.
bridge_sampler(object) returns the original upstream bridge object;
it does not promise the stored wrapper's optional telemetry field.
Product-space model-averaging objects (BMA.norm, BMA.glmm,
BMA.mv, RoBMA, and RoBMA.mv) do not expose a
bridge-sampling marginal likelihood;
use predictive comparison methods such as loo.brma instead.
For a single model whose bridge parameters are all fixed by point priors,
the log marginal likelihood is evaluated exactly at those fixed values;
no bridge-sampling repetitions are required.
For brma.mv() known-V objects, bridge sampling evaluates the
joint likelihood corresponding to the fitted known-V backend, not the
conditional estimate-wise target used by LOO/WAIC diagnostics. Sampled
Gaussian location random-effect blocks are integrated exactly during bridge
evaluation as their draw-specific ZGZ' covariance. Their SD,
allocation, and correlation parameters remain bridge coordinates; only the
standardized latent effects are removed. This is a reparameterization of the
same marginal-likelihood target, not a likelihood approximation. Fitted
estimate-level marginalized blocks remain in the diagonal row variance.
For Gaussian models fitted with the specialized cluster interface,
the standardized cluster effects are likewise integrated exactly. The bridge
retains total heterogeneity and its allocation while evaluating the implied
diagonal-plus-cluster-rank-one covariance, including row-specific scale
regression and likelihood weights.
Selection models retain every context that the fitted model conditions on,
including its normalized prior, and integrate only the Gaussian sources
declared by that model. The likelihood uses the same full publication events
and integration plan as fitting. A context integrated before selection
normalization cannot be replaced by a retained-context parameterization.
With known_sampling_variance = "condition", the bridge retains the
independent Gaussian augmentation coordinates and their normalized priors.
The complete sampling error and random effects are reconstructed for each
proposed bridge state before evaluating its selection normalizer.
A non-finite bridge repetition raises a
RoBMA_marglik_repetition_failure error, inheriting from
RoBMA_marglik_error. Its parent retains the complete upstream
condition, including the failed repetitions table. Increase
maxiter when a failed repetition reached its iteration limit;
otherwise inspect the posterior samples and priors for non-finite densities.
Fitting more posterior draws (for example with a larger sample or
update()) may help in either case. These actions do not guarantee
that the diagnostics will pass.
A checked posterior sample that cannot form a full-rank bridge proposal
raises RoBMA_marglik_rank_deficiency, inheriting from
RoBMA_marglik_error. Its unchanged upstream parent and exposed
reason, rank, n_coordinates, n_draws, and
dependent_coordinates describe the observed sample. For
reason = "insufficient_draws", fit more posterior draws with a larger
sample or update(); dependence may persist. For
reason = "dependent_coordinates", inspect the parameterization and
sampling; more draws alone need not resolve dependence. The message names the
first reported pivot coordinates; they identify one dependent set, not
uniquely faulty nodes.
The stored result records an identity of the data, weights, priors, and
model it was computed for. bridge_sampler(), logml(),
bf(), and post_prob() refuse a stored result that no longer
matches the object, or that an earlier RoBMA version stored, with an error of
class RoBMA_marglik_stale (inheriting from RoBMA_marglik_error);
recompute it with add_marglik(). update(slab = ) keeps it, and
extending the fit with update() recomputes or drops it.
Value
The brma object with the marginal likelihood result stored in
object[["marglik"]].
See Also
bridge_sampler.brma, logml.brma,
bf.brma, post_prob.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_marglik(fit)
bridge <- bridge_sampler(fit)
print(bridge)
logml(fit)
}
## End(Not run)
Add WAIC to brma Objects
Description
Compute the Widely Applicable Information Criterion (WAIC) for brma model objects and store the result in the object.
Usage
## S3 method for class 'brma'
add_waic(object, unit = "estimate", ...)
Arguments
object |
a brma model object. |
unit |
output/deletion unit. See |
... |
additional arguments passed to |
Details
WAIC is an alternative to LOO-CV for estimating out-of-sample predictive accuracy. Like LOO, it evaluates expected predictive performance for new observations.
In most cases, LOO-PSIS (via add_loo) is preferred over WAIC
because it provides better estimates and includes diagnostics (Pareto k
values) that indicate when the approximation may be unreliable.
For Gaussian multilevel and known-V brma.mv() models,
estimate-unit WAIC uses the same integrated conditional log-likelihood matrix
as estimate-unit LOO, p(y_i \mid y_{-i}, \theta). Estimate deletion
retains the fitted grouping and dependency structure. Weighted Gaussian
cluster models integrate the powered row likelihood, with its normalizing
constant, over the retained-data cluster-effect distribution. Earlier stored
weighted estimate-unit WAIC results require recomputation with add_waic().
For brma.mv() models with known random-effect group covariance
R, the known R matrix and fitted random-effect covariance enter
through BayesTools' metadata-defined marginal ZGZ' covariance. The same
four-field comparison policy applies across sampled, marginalized, and mixed
local-effect representations.
Value
The brma object with the WAIC result stored in
object[["waic"]][[unit]].
See Also
Convert brma Summaries to a Data Frame
Description
Converts the non-empty tables displayed by a fitted
brma object or its summary.brma result to one plain,
long-form data frame. The leading
component column identifies the summary section and
parameter retains the displayed row label. Printed quantile labels
are returned as syntactic CI_ column names.
Usage
## S3 method for class 'brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
## S3 method for class 'summary.brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
Arguments
x |
a fitted |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
for a fitted object, additional arguments passed to
|
Value
A plain data.frame containing all displayed summary rows.
An object created with only_data = TRUE or only_priors = TRUE
has no fitted model to export and stops with an error of class
RoBMA_unfitted_object (also of class
RoBMA_unsupported_request); summary() shows the data of an
only_data object, and the summary of an only_priors object
shows the priors in its priors element.
Convert brma_samples Results to Data Frames
Description
as.data.frame() and data.frame() of a
brma_samples result return its posterior draws (one row per draw, one
column per parameter), as for the underlying matrix. The posterior summary
table displayed by print() is as.data.frame(summary(x)): a
long data frame with component and parameter identifiers (multi-component
paths use / as a separator), which is also the result for a
multi-component brma_samples_list. Printed quantile labels
such as 0.025 and PI 0.025 are returned as the syntactic column
names CI_0.025 and PI_0.025, respectively.
Usage
## S3 method for class 'brma_samples'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)
## S3 method for class 'summary.brma_samples'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
## S3 method for class 'brma_samples_list'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
format = c("long", "list"),
stringsAsFactors = FALSE,
...
)
Arguments
x |
a |
row.names |
|
optional |
logical; passed to the final data-frame coercion method. |
... |
for a |
stringsAsFactors |
logical; passed to the output data frame. |
format |
for multi-component results, whether to return a single
|
Value
For an individual brma_samples object, a data.frame
of the posterior draws. For a summary.brma_samples object, a plain
long data.frame containing the displayed posterior summary statistics
and leading component and parameter columns.
For a brma_samples_list, a long data frame by default or, with
format = "list", a named, possibly nested list of such data frames.
Convert COVRATIO Results to a Data Frame
Description
Converts a covratio.brma vector to a component-aware
long data frame.
Usage
## S3 method for class 'covratio.brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
Arguments
x |
a |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
unused additional arguments. |
Value
A plain data.frame with leading component and
parameter columns and a numeric value column.
Convert DFBETAS Results to a Data Frame
Description
Converts a dfbetas.brma object to a component-aware
long data frame while retaining its displayed coefficient columns.
Usage
## S3 method for class 'dfbetas.brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
Arguments
x |
a |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
unused additional arguments. |
Value
A plain data.frame with leading component and
parameter columns.
Convert Influence Results to a Data Frame
Description
Converts the influence and DFBETAS tables displayed by an
infl.brma object to one component-aware long data frame.
Usage
## S3 method for class 'infl.brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
Arguments
x |
an |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
unused additional arguments. |
Value
A plain data.frame with leading component and
parameter columns.
Convert Marginal Means to a Data Frame
Description
Converts the summary displayed for a
marginal_means.brma object to a plain long data frame with leading
component and parameter columns. Printed quantile labels are
returned as syntactic CI_ column names.
Usage
## S3 method for class 'marginal_means.brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
## S3 method for class 'summary.marginal_means.brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
Arguments
x |
a |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
additional arguments passed to |
Value
A plain long data.frame containing the displayed
marginal-means summary and leading component and parameter
columns.
Convert Heterogeneity Summaries to Data Frames
Description
Converts heterogeneity summaries to plain long data frames with
leading component and parameter columns. A multi-component
result can instead be returned as a named list with
format = "list".
Usage
## S3 method for class 'summary_heterogeneity.brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
## S3 method for class 'summary_heterogeneity.brma_list'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
format = c("long", "list"),
stringsAsFactors = FALSE,
...
)
Arguments
x |
a |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
unused additional arguments. |
format |
for multi-component results, whether to return one
|
Value
A plain data.frame, or a named list of data frames when
format = "list".
Convert Model-Weight Summaries to a Data Frame
Description
Converts every table displayed by a
summary_models.RoBMA object to one component-aware long data frame.
Usage
## S3 method for class 'summary_models.RoBMA'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
Arguments
x |
a |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
unused additional arguments. |
Value
A plain data.frame with leading component and
parameter columns.
Convert VIF Results to a Data Frame
Description
Converts every table displayed by a vif.brma object to
one component-aware long data frame.
Usage
## S3 method for class 'vif.brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
Arguments
x |
a |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
unused additional arguments. |
Value
A plain data.frame with leading component and
parameter columns.
Convert Z-Plot Summaries to a Data Frame
Description
Converts the table displayed for a zplot_brma or
summary.zplot_brma object to a component-aware long data frame.
Printed quantile labels are returned as syntactic CI_ column names.
Usage
## S3 method for class 'zplot_brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
## S3 method for class 'summary.zplot_brma'
as.data.frame(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...
)
Arguments
x |
a |
row.names |
|
optional |
logical; passed to the final data-frame coercion. |
stringsAsFactors |
accepted for compatibility with |
... |
additional arguments passed to |
Value
A plain data.frame with leading component and
parameter columns.
Convert brma_samples to Matrix
Description
Converts a brma_samples object to a plain matrix,
removing all brma_samples-specific attributes.
Usage
## S3 method for class 'brma_samples'
as.matrix(x, ...)
Arguments
x |
a |
... |
additional arguments (ignored) |
Value
A plain matrix of posterior samples.
Convert brma Objects to posterior Draws Formats
Description
Provides an interface to the posterior package
for brma objects. These functions convert the MCMC samples
from a fitted brma model to various draws formats supported
by the posterior package, enabling the use of posterior's
rich set of diagnostics and summary functions.
Usage
as_draws(x, ...)
as_draws_array(x, ...)
as_draws_df(x, ...)
as_draws_list(x, ...)
as_draws_matrix(x, ...)
as_draws_rvars(x, ...)
## Default S3 method:
as_draws(x, ...)
## Default S3 method:
as_draws_array(x, ...)
## Default S3 method:
as_draws_df(x, ...)
## Default S3 method:
as_draws_list(x, ...)
## Default S3 method:
as_draws_matrix(x, ...)
## Default S3 method:
as_draws_rvars(x, ...)
## S3 method for class 'brma'
as_draws(x, include_auxiliary = FALSE, ...)
## S3 method for class 'brma'
as_draws_array(x, include_auxiliary = FALSE, ...)
## S3 method for class 'brma'
as_draws_df(x, include_auxiliary = FALSE, ...)
## S3 method for class 'brma'
as_draws_list(x, include_auxiliary = FALSE, ...)
## S3 method for class 'brma'
as_draws_matrix(x, include_auxiliary = FALSE, ...)
## S3 method for class 'brma'
as_draws_rvars(x, include_auxiliary = FALSE, ...)
Arguments
x |
an object to convert. The |
... |
additional arguments passed to the corresponding posterior function. |
include_auxiliary |
logical; whether to include the hidden
intermediate parameters (see Details) in addition to the parameters shown by
the default |
Details
By default, the draws hold exactly the parameters that the default
print() and summary() of the fit show (the location, heterogeneity,
and moderator coefficients, the multilevel allocation rho, and the
publication-bias parameters), together with the model-inclusion indicators
behind the reported inclusion probabilities. The hidden intermediate
parameters are added by include_auxiliary = TRUE: the latent
cluster and estimate effects (gamma[k] and the GLMM theta[i]),
the selection-model latent variables (eta), the GLMM nuisance base
rates and rates (pi[i] and phi[i]), the random-effect
variances, component SDs derived from a variance allocation, and total
variance of formula-random models (for example tau2 or
tau2_total), and the other backend variables listed below.
These functions are S3 generics. Their default methods forward to the
corresponding posterior generics so attaching RoBMA preserves
the usual posterior behavior for non-brma objects.
The following conversion functions are available:
-
as_draws: converts to the default draws format -
as_draws_array: converts to a 3-D array (iteration x chain x variable) -
as_draws_df: converts to a data frame with columns for iterations, chains, and variables -
as_draws_list: converts to a list of lists -
as_draws_matrix: converts to a 2-D matrix (draw x variable) -
as_draws_rvars: converts to random variable objects
These methods require the posterior package to be installed.
For brma methods, conversion is performed by first extracting the MCMC
samples as a mcmc.list object and then using the corresponding
posterior conversion function. By default, backend-private latent
effects, known-V dependency factors, random-effect simulation and
Cholesky factors, and prior-parameterization variables are omitted. Stable
fitted coordinates such as model indicators remain available.
Ordinary spike-and-slab backend slab and inclusion
coordinates are omitted by default; include_auxiliary = TRUE retains
them. Semantic random-effect indicators remain available as described below.
Formula-random coordinates are replaced by their semantic
RoBMA quantities using the same names as summaries, plots, and hypotheses,
such as tau_total, tau_common, rho(...), and tau2_prop(...).
A rho(...) column can contain NA draws: an original-scale correlation
is undefined in draws where one of its standard deviations is zero, e.g.
where an inclusion gate or a point prior sets it to zero. Summaries
and hypothesis tests of the correlation use its defined draws; summaries
computed from the exported draws need to handle the NA values.
Random-effect SD switches are exposed as exact columns named after the
standard deviation they act on, with an _indicator suffix, pairing with
the semantic SD column the same way mu_x_indicator pairs with mu_x. A
heterogeneity-component inclusion gate is 0/1, such as study: tau_indicator
and observation: tau_indicator, and carries the inclusion state the
summary reports under Heterogeneity:. An allocation-SD prior indicator,
such as tau_total_indicator, records which mixture component allocated the
total standard deviation and therefore takes one value per component,
matching the order of that prior's components.
Ordered predictor terms return their fitted totals and normalized sampled
allocation shares by default, replacing their deterministic increment
coordinates. Shares are normalized from the sampled Gamma primitives and
remain defined when a total is zero or its inclusion event is off. Totals
with point priors are exact constants for every fitted slice; fixed
allocations do not create share columns. The labels come from the fitted
BayesTools ordered specification, including reached factor levels and
interaction slices. These quantities remain on the fitted predictor scale.
Ordered-total mixture indicators and inclusion probabilities remain
available, while nested slab and pseudo-prior coordinates are omitted.
With include_auxiliary = TRUE, raw ordered increments and eligible
total auxiliaries are also retained. Internal Gamma coordinates are never
exported. as_draws_rvars() preserves allocation labels as scalar
random variables and keeps ordinary vector and multi-slice total indices.
If an ordered sampled parameter conflicts with an existing fitted column,
conversion stops with classes RoBMA_ordered_draws_conflict and
RoBMA_ordered_draws_unavailable, with the message
Ordered sampled parameter '<name>' conflicts with existing fitted draws. Refit the model with the current RoBMA/BayesTools build.
Missing required ordered sources stop with
RoBMA_ordered_draws_unavailable and
BayesTools_ordered_coordinates_unavailable, with parent class
BayesTools_ordered_unavailable and the message
Ordered source draws are unavailable. Refit the model with the current RoBMA/BayesTools build.
Entirely fixed numeric-point terms need only the existing chain row count
to materialize their declared totals.
Both RoBMA ordered refit errors also inherit RoBMA_refit_required
and BayesTools_refit_required.
Structural point-prior coordinates are returned as exact constant columns,
with chain timing taken from the fitted draw geometry. Private backend
anchors are never exposed. Use include_auxiliary = TRUE to skip RoBMA
auxiliary filtering; added backend variables retain their coordinate names,
while public random-effect parameters retain their RoBMA names.
brma_samples objects have
separate methods documented at as_draws.brma_samples.
Value
An object of the corresponding posterior draws class.
See Also
draws, brma,
as_draws.brma_samples
Convert brma_samples to posterior Draws Formats
Description
Provides an interface to the posterior package
for brma_samples objects. These functions convert the posterior
samples to various draws formats supported by the posterior package.
Usage
## S3 method for class 'brma_samples'
as_draws(x, ...)
## S3 method for class 'brma_samples'
as_draws_array(x, ...)
## S3 method for class 'brma_samples'
as_draws_df(x, ...)
## S3 method for class 'brma_samples'
as_draws_list(x, ...)
## S3 method for class 'brma_samples'
as_draws_matrix(x, ...)
## S3 method for class 'brma_samples'
as_draws_rvars(x, ...)
Arguments
x |
a |
... |
additional arguments passed to the corresponding posterior function |
Details
The conversion reconstructs the MCMC chain structure from the stored
nchains and niter attributes. The samples are assumed
to be ordered with chains concatenated (i.e., all iterations from chain 1,
then all from chain 2, etc.). Conditional RoBMA samples are intentionally
stored as one flattened chain because conditioning subsets posterior rows
across chains.
The generic as_draws() returns a draws_matrix, which retains
the chain counts in its metadata; request as_draws_array() for the
chain-by-iteration array.
Value
An object of the corresponding posterior draws class.
See Also
Prepare brma Data for metafor Forest Plots
Description
as_metafor_forest extracts observed effect sizes,
standard errors, study labels, and RoBMA posterior summary intervals in a
structure that can be passed to metafor's forest plotting functions.
Usage
as_metafor_forest(x, ...)
## S3 method for class 'brma'
as_metafor_forest(
x,
level = 95,
addpred = FALSE,
newdata = NULL,
bias_adjusted = TRUE,
conditional = FALSE,
...
)
Arguments
x |
a fitted brma object. |
... |
additional named arguments stored in |
level |
credible/confidence level in percent, greater than 0 and less
than 100. A value below 1 is read as a proportion ( |
addpred |
logical; whether to compute a marginal posterior prediction
interval for one new true effect. Defaults to |
newdata |
optional one-row prediction design used when
|
bias_adjusted |
logical; whether pooled and prediction summaries should
adjust for publication bias. Defaults to |
conditional |
logical; whether to return conditional posterior
summaries for RoBMA product-space objects. Defaults to |
Value
A list of class metafor_forest.brma with study-level data,
pooled posterior summaries, and ready-to-use argument lists for
forest.default and
addpoly.default. The forest_args include
enough vertical space for the default summary row. The returned object can
also be plotted directly with forest.
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(yi = yi, vi = vi, data = dat, measure = "RR")
count_columns <- as.matrix(dat[, c("tpos", "tneg", "cpos", "cneg")])
forest_data <- as_metafor_forest(
fit,
addpred = TRUE,
slab = paste(dat$author, dat$year),
ilab = count_columns,
ilab.lab = c("T+", "T-", "C+", "C-"),
ilab.xpos = c(-7, -6, -5, -4),
xlim = c(-10, 4),
atransf = exp
)
metafor::forest(forest_data, predstyle = "bar")
# Or draw the metafor calls directly:
do.call(metafor::forest.default, forest_data$forest_args)
do.call(metafor::addpoly.default, forest_data$addpoly_args)
}
## End(Not run)
Transform brma Object to Zplot
Description
Transforms an estimated brma model into a zplot object that can be summarized and plotted to assess replicability.
Usage
## S3 method for class 'brma'
as_zplot(
object,
significance_level = stats::qnorm(0.975),
max_samples = 10000,
conditioning_depth = "marginal",
integration_control = set_selection_likelihood_control(),
...
)
Arguments
object |
a normal-outcome |
significance_level |
positive z-value threshold for significance.
Defaults to |
max_samples |
maximum number of posterior samples for the EDR and
missing-study summaries. Defaults to 10000. Use |
conditioning_depth |
predictive conditioning depth. Options are
|
integration_control |
numerical integration settings created by
|
... |
additional arguments (currently unused). |
Details
Zplot is the pushforward into z-space of the design-conditional posterior
predictive distribution. It retains the empirical mix of observed standard
errors and moderators, evaluates one row-specific predictive distribution
for each estimate, transforms each through Z = Y / SE, and averages
the resulting densities with equal weight per estimate.
The default marginal target integrates every latent effect that would be
newly realized in a replicated literature. For a specialized multilevel
model fitted with cluster,
the predictive variance before sampling error is the sum of between- and
within-cluster heterogeneity. Cluster conditioning instead retains the fitted
cluster effects and includes only within-cluster heterogeneity. Estimate
conditioning uses the conditional true-effect means returned by
predict(type = "blup") and additionally integrates the posterior
conditional variance of those latent effects before adding new sampling
error. It therefore represents a posterior predictive replication of the
same uncertain latent effects rather than a BLUP-mean plug-in distribution.
Thus the marginal zplot collapses the row-specific slices of the marginal
funnel target onto the common significance scale. Unlike LOO diagnostics,
it is a full-posterior predictive projection and does not leave observations
or clusters out when estimating model parameters.
The Expected Discovery Rate (EDR) is the posterior average probability that
a new outcome from the bias-adjusted reference distribution is statistically
significant at the supplied threshold. It is therefore not an exact-repeat
estimand unless conditioning_depth = "estimate" is requested.
The EDR uses the bias-adjusted reference distribution: selection and
PET/PEESE offsets are removed. For multivariate selection models, models
retaining estimate-level or sampling-error sources or integrating applicable
contextual sources, and best-rule selection models, this reference is the
normalized pre-selection Gaussian marginal,
integrating all newly realized contexts. Its integral is
one and EDR is its significance probability. Relative selection weights do
not identify an absolute publication probability or missing count, so
Missing N is unavailable for these targets.
The fitted selected curve preserves the original publication event and the fitted model's normalization order. It integrates the model's integrated sources inside each full-event normalizer and averages conditionally normalized projections over newly realized retained contexts. A best rule still selects the full original event when displaying one estimate. Supported full-covariance product blocks reuse numerator and normalizer calculations while refining their quadrature separately. Computation by posterior row and covariance block preserves the full publication event.
Numerical diagnostics distinguish raw normalizer-mass ratios from bounds on omitted contributions. A raw mass ratio does not certify that the compressed displayed curve integrates to one. An omitted-mass bound covers only the omitted components, not the total integrated error of the compressed curve. Retained component weights are not renormalized to hide omissions.
Independent univariate product-weight models and the released conditional
cluster display retain their reference-bin-normalized inverse-weight
extrapolation convention and corresponding Missing N summary.
Product selection does not use publication groups; its covariance
dependencies and source settings determine the reference distribution and
diagnostic. Best-p-value selection preserves the resolved publication groups.
A literal count interpretation additionally treats the reference bin as
fully observed and requires a reporting/stopping design relating attempted
to observed estimates. These assumptions are not supplied by the fitted
relative-weight likelihood, which conditions on the reported vector and
does not identify an absolute publication probability or finite missing pool.
Valid above-one relative weights can give a negative diagnostic; such a
value is not a literal missing count.
Restricting a plot with from or to does not restrict the
summary integrals.
Zplot diagnostics are available only for normal outcome models. GLMM
objects are rejected because their raw likelihood is on a count scale while
zplot diagnostics require observed effect-size z-statistics with standard
errors. For correlated known-V brma.mv() models, zplot is a
scalar display using z_i = y_i / se_i. The histogram does not display
dependence, but the fitted selected marginals retain the full covariance.
Numerical integration can be substantially more expensive for correlated
selection than for ordinary Gaussian models. Density plotting uses its own
max_samples argument, independently of the summaries stored here.
The resulting object retains all original brma properties while adding zplot results, enabling both standard meta-analytic summaries and zplot diagnostics on the same object.
Value
The input object with added class "zplot_brma" and a new
zplot list component containing:
- estimates
a list with posterior samples for
EDRand extrapolationweights, when a missing-count convention applies- data
a list with
significance_level,conditioning_depth, storedintegration_control, observedz-statistics,N_significant, andN_observed- target
the fitted reporting specification, reference distribution, source and publication identities, and missing-count applicability
See Also
summary.zplot_brma(), plot.zplot_brma(), hist.zplot_brma(),
predict.brma(), funnel.brma(), regplot.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
zfit <- as_zplot(fit)
summary(zfit)
plot(zfit)
}
## End(Not run)
Bayesian Precision-Effect Estimate with Standard Errors (PEESE) Model
Description
Function for fitting random-effects, meta-regression, multilevel, and location-scale meta-analytic PEESE models.
Usage
bPEESE(
yi,
vi,
sei,
weights,
ni,
mods,
scale,
cluster,
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_heterogeneity_allocation,
prior_bias,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
effect_direction = "detect",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
...
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_heterogeneity_allocation |
prior distribution for the fraction of
heterogeneity allocated to the cluster-level component in multilevel models
( |
prior_bias |
PEESE regression-coefficient prior created by
|
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
effect_direction |
direction used by publication-bias adjustments.
|
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
Value
A fitted object of class c("bPEESE", "brma") containing a single
PEESE publication-bias model fit.
See Also
bPEESE.mv(), publication_bias_prior_specification, RoBMA(),
bPET(), bselmodel(), summary.brma(), funnel.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPEESE(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
summary(fit)
funnel(fit)
}
## End(Not run)
Bayesian Multivariate and Multilevel PEESE Model
Description
Fits Bayesian precision-effect estimate with standard errors (PEESE) models with known sampling covariance and BayesTools random-effect formulas.
Usage
bPEESE.mv(
yi,
V,
ni,
mods,
scale,
random,
R = NULL,
Rscale = "cor",
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_bias,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
effect_direction = "detect",
known_v_parameterization = "auto",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
...,
vi = NULL,
sei = NULL
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
V |
a known working variance-covariance matrix, a list of block
variance-covariance matrices, or an exact diagonal-plus-factor declaration
created by |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
random |
Optional BayesTools random-effect formula or list of formulas.
Omission or |
R |
optional known random-effect group covariance/correlation matrix,
or a named list of matrices. Matrix row and column names identify grouping
levels. This is distinct from the known sampling covariance |
Rscale |
scaling applied to each supplied |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_bias |
PEESE regression-coefficient prior created by
|
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
effect_direction |
direction used by publication-bias adjustments.
|
known_v_parameterization |
known- |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
Details
Omitted or NULL random specifies a fixed-effect model with no implicit
heterogeneity. Heterogeneity priors and scale formulas require an explicit
random structure; the known sampling covariance remains unchanged.
bPEESE.mv() combines the PEESE publication-bias regression of bPEESE()
with the known-covariance and random-formula model of brma.mv(). The PEESE
predictor is the marginal sampling variance diag(V); known off-diagonal
sampling covariance remains part of the joint likelihood.
The supported known-V backends, random-effect marginalization rules,
predictive targets, and diagnostic semantics are the same as for
brma.mv(). In particular, random replaces the specialized cluster
argument used by bPEESE().
Value
A fitted object of class
c("bPEESE.mv", "bPEESE", "brma.mv", "brma.norm", "brma").
See Also
bPEESE(), bPET.mv(), brma.mv(), summary.brma()
Examples
## Not run:
V <- matrix(c(0.04, 0.01, 0.01, 0.09), 2, 2)
fit <- bPEESE.mv(
yi = c(0.10, 0.20),
V = V,
measure = "GEN",
seed = 1,
silent = TRUE
)
summary(fit)
## End(Not run)
Bayesian Precision-Effect Test (PET) Model
Description
Function for fitting random-effects, meta-regression, multilevel, and location-scale meta-analytic PET models.
Usage
bPET(
yi,
vi,
sei,
weights,
ni,
mods,
scale,
cluster,
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_heterogeneity_allocation,
prior_bias,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
effect_direction = "detect",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
...
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_heterogeneity_allocation |
prior distribution for the fraction of
heterogeneity allocated to the cluster-level component in multilevel models
( |
prior_bias |
PET regression-coefficient prior created by
|
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
effect_direction |
direction used by publication-bias adjustments.
|
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
Value
A fitted object of class c("bPET", "brma") containing a single
PET publication-bias model fit.
See Also
bPET.mv(), publication_bias_prior_specification, RoBMA(),
bPEESE(), bselmodel(), summary.brma(), funnel.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
summary(fit)
funnel(fit)
}
## End(Not run)
Bayesian Multivariate and Multilevel PET Model
Description
Fits Bayesian precision-effect test (PET) models with known sampling covariance and BayesTools random-effect formulas.
Usage
bPET.mv(
yi,
V,
ni,
mods,
scale,
random,
R = NULL,
Rscale = "cor",
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_bias,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
effect_direction = "detect",
known_v_parameterization = "auto",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
...,
vi = NULL,
sei = NULL
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
V |
a known working variance-covariance matrix, a list of block
variance-covariance matrices, or an exact diagonal-plus-factor declaration
created by |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
random |
Optional BayesTools random-effect formula or list of formulas.
Omission or |
R |
optional known random-effect group covariance/correlation matrix,
or a named list of matrices. Matrix row and column names identify grouping
levels. This is distinct from the known sampling covariance |
Rscale |
scaling applied to each supplied |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_bias |
PET regression-coefficient prior created by
|
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
effect_direction |
direction used by publication-bias adjustments.
|
known_v_parameterization |
known- |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
Details
Omitted or NULL random specifies a fixed-effect model with no implicit
heterogeneity. Heterogeneity priors and scale formulas require an explicit
random structure; the known sampling covariance remains unchanged.
bPET.mv() combines the PET publication-bias regression of bPET() with
the known-covariance and random-formula model of brma.mv(). The PET
predictor is the marginal sampling standard error sqrt(diag(V)); known
off-diagonal sampling covariance remains part of the joint likelihood.
The supported known-V backends, random-effect marginalization rules,
predictive targets, and diagnostic semantics are the same as for
brma.mv(). In particular, random replaces the specialized cluster
argument used by bPET().
Value
A fitted object of class
c("bPET.mv", "bPET", "brma.mv", "brma.norm", "brma").
See Also
bPET(), bPEESE.mv(), brma.mv(), summary.brma()
Examples
## Not run:
V <- matrix(c(0.04, 0.01, 0.01, 0.09), 2, 2)
fit <- bPET.mv(
yi = c(0.10, 0.20),
V = V,
measure = "GEN",
seed = 1,
silent = TRUE
)
summary(fit)
## End(Not run)
Bayes Factor for brma Objects
Description
Compute the Bayes factor comparing two brma models.
Usage
## S3 method for class 'brma'
bf(x1, x2, log = FALSE, ...)
## S3 method for class 'brma'
bayes_factor(x1, x2, log = FALSE, ...)
Arguments
x1 |
a brma model object (numerator). |
x2 |
a brma model object (denominator). |
log |
logical; if |
... |
additional arguments (currently not used). |
Details
Computes the Bayes factor in favor of the model x1 over the
model x2. The marginal likelihoods must first be computed using
add_marglik. Both models must be fitted to the same
outcome target/data, including outcome type and, when present, likelihood
weights. Cluster identifiers define model structure and are not part of the
outcome-data identity. A known sampling covariance without correlated blocks
(e.g., V = diag(sei^2) in brma.mv) is the outcome data
of its standard errors, whereas a correlated V is a different target.
When either model contains repeated bridge estimates, the shorter sequence
is recycled with a warning, following bridgesampling. Repetitions are
compared in order. The median-based estimate is computed from the separate
medians of the log marginal likelihoods before recycling, rather than the
median of the repetition-wise Bayes factors. Standardized
marginal-likelihood results must be finite. Legacy raw
"bridge_list" results retain failed repetitions in the returned
estimates, with upstream missing-value behavior when printed.
Value
For single estimates, a list of class "bf_default" with components:
-
bf: (scalar) value of the Bayes factor in favor ofx1overx2. -
log: Boolean indicating whetherbfcorresponds to the log Bayes factor.
For repeated estimates, a list of class c("bf.brma", "bf_bridge_list")
with a vector bf, scalar bf_median_based, and log. It
uses the upstream repeated-Bayes-factor print method. Both
as.data.frame() and data.frame() return a long data frame with
component, parameter, and full-precision numeric value
columns, containing every repetition and the displayed median-based, range,
and interquartile-range summaries.
See Also
add_marglik, bridge_sampler.brma,
post_prob.brma, logml.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit1 <- brma(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit2 <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
prior_effect = FALSE
)
fit1 <- add_marglik(fit1)
fit2 <- add_marglik(fit2)
bf(fit1, fit2)
}
## End(Not run)
Best Linear Unbiased Predictions (BLUPs)
Description
Computes the estimated true effects (theta) from a fitted model. These correspond to Best Linear Unbiased Predictions (BLUPs) or empirical Bayes estimates.
Usage
blup(object, ...)
Arguments
object |
a fitted model object |
... |
additional arguments passed to methods |
Value
Method-specific return value, typically a summary table or posterior samples of BLUP or empirical-Bayes true-effect summaries.
See Also
Best Linear Unbiased Predictions for brma Objects
Description
Computes the estimated true effects (theta) for a fitted brma object. These correspond to Best Linear Unbiased Predictions (BLUPs) or empirical Bayes estimates.
Usage
## S3 method for class 'brma'
blup(
object,
bias_adjusted = FALSE,
output_measure = NULL,
transform = NULL,
probs = c(0.025, 0.975),
...
)
Arguments
object |
a fitted brma object |
bias_adjusted |
whether to adjust for publication bias. Defaults to
|
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
probs |
quantiles of the posterior distribution to be displayed.
Defaults to |
... |
additional arguments passed to |
Details
This function is a convenience wrapper around predict.brma(...,
type = "blup", newdata = NULL). Unlike predict(..., type =
"estimate", conditioning_depth = "estimate"), it returns conditional
location/BLUP means rather than adding conditional latent-effect uncertainty.
For unweighted two-level normal models, true effects are computed using empirical Bayes shrinkage:
\theta_i = \lambda_i \cdot y_i + (1 - \lambda_i) \cdot \mu_i
where \lambda_i = \tau^2 / (\tau^2 + se_i^2).
With likelihood weights, se_i^2 is replaced by the weighted sampling
variance se_i^2 / w_i.
For GLMM models (binomial, Poisson), the estimate-level random effects are extracted directly from the posterior samples.
For multilevel (3-level) normal models, cluster-level effects are estimated jointly within cluster blocks and estimate-level effects are then shrunk conditional on those cluster effects.
For known-V models, the conditional means require applying the
inverse of the marginal covariance. A covariance that is too ill-conditioned
for that (a reciprocal condition number of about 2e-10 or less in any
posterior draw used) is unavailable: the call stops with an error of class
RoBMA_known_v_precision_unavailable, whose parent class is
RoBMA_numerical_unavailable, instead of returning a rounded number.
The condition carries the draw positions (rows) and their
reciprocal_condition.
Value
A brma_samples object containing posterior draws of BLUP or
empirical-Bayes true-effect summaries with one column per estimate. For
existing normal data, these are conditional BLUP means, not simulated
latent-effect draws. When printed, displays a summary table. Use
summary(), or as.data.frame(summary(x)), to obtain the summary
table; as.data.frame(x) returns the posterior draws. The samples can be
converted to posterior draws formats using as_draws().
See Also
predict.brma(), pooled_effect(), pooled_heterogeneity(),
true_effects()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
blup(fit)
}
## End(Not run)
Bridge Sampling for brma Objects
Description
Extract the marginal likelihood bridge sampling object from
a brma model. The marginal likelihood must first be computed using
add_marglik.
Usage
## S3 method for class 'brma'
bridge_sampler(samples, ...)
Arguments
samples |
a brma model object. |
... |
additional arguments (currently not used). |
Details
This function extracts the raw bridgesampling object underlying the
marginal-likelihood result stored by add_marglik. If the
marginal likelihood has not been computed, an error is thrown.
Product-space model-averaging objects (BMA.norm, BMA.glmm,
BMA.mv, RoBMA, and RoBMA.mv) do not expose
bridge-sampling marginal likelihoods.
Fully fixed models can have a zero-dimensional marginal likelihood evaluated
exactly. Such fits have no bridge-sampling object, so this method raises a
RoBMA_exact_marglik_no_bridge error; use logml to
retrieve their exact log marginal likelihood. For Bayesian model comparison,
pass fitted brma objects directly to bf or
post_prob.
When a stored marginal-likelihood result has no raw bridge object,
extraction raises RoBMA_bridge_unavailable.
Its reason is "exact_zero_dimensional" for an exact result,
or "missing_upstream" when a stored result lacks its raw bridge
object. For the latter, recompute the result with add_marglik.
Value
An object of class "bridge", or "bridge_list" for
repeated bridge estimates, as returned by
bridge_sampler.
See Also
add_marglik, bridge_sampler,
logml.brma, bf.brma, post_prob.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_marglik(fit)
bridge <- bridge_sampler(fit)
print(bridge)
}
## End(Not run)
Bayesian Meta-Analysis
Description
Function for fitting normal-likelihood/effect-size
random-effects, meta-regression, multilevel, and location-scale
meta-analytic models. brma.norm() is an alias for brma(); raw-count
GLMM models use brma.glmm().
Usage
brma(
yi,
vi,
sei,
weights,
ni,
mods,
scale,
cluster,
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_heterogeneity_allocation,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
...
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_heterogeneity_allocation |
prior distribution for the fraction of
heterogeneity allocated to the cluster-level component in multilevel models
( |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
Details
Prior distributions
Prior distributions must be specified for all model parameters.
This typically includes the pooled effect \mu and between-study heterogeneity
\tau. In the case of meta-regression, the pooled effect \mu corresponds to
the intercept, and additional prior distributions for the regression coefficients
are required. In the case of a location-scale model, the between-study heterogeneity
corresponds to the intercept of the scale regression, and additional prior
distributions for the scale regression coefficients are required.
There are several ways to specify the prior distributions:
via a standardized effect size
measurewith known unit information standard deviation,by estimating unit information standard deviation using sample sizes
ni,by manually setting
prior_unit_information_sd,by specifying informed empirical prior distributions via
prior_informed_fieldandprior_informed_subfield,or via fully custom specification using the
prior_effect,prior_heterogeneity,prior_mods,prior_scale, andprior_heterogeneity_allocationarguments.
In all cases, the prior behavior can be further modified by the rescale_priors,
standardize_continuous_predictors, and set_contrast_factor_predictors arguments.
(1) Specifying prior distributions via standardized effect size measures with known
unit information standard deviation
This is the easiest way to specify prior distributions. The width of prior
distributions is based on a fraction of the known unit information standard deviation (UISD)
(Röver et al. 2021). The default prior distributions for the parameters
are set as follows:
| effect size: | Normal(0, \frac{1}{2} UISD) |
| heterogeneity: | Normal+(0, \frac{1}{4} UISD) |
| effect moderation: | Normal(0, \frac{1}{4} UISD) |
| heterogeneity moderation: | Normal(0, \frac{1}{2})
|
The heterogeneity moderation parameters are multiplicative, as such they are independent of UISD.
The default fraction of the UISD can be changed via RoBMA.options() using one of
the following arguments: "default_UISD.effect", "default_UISD.heterogeneity",
"default_UISD.mods", "default_UISD.scale".
The known UISD for standardized effect size measures (measure) are set as follows:
"SMD": | \sqrt{2} |
"ZCOR": | 1 |
"RR": | \sqrt{4} |
"OR": | \sqrt{4} |
"HR": | \sqrt{4} |
"IRR": | \sqrt{4}
|
See Chapter 2.4 in Spiegelhalter et al. (2004) and Chapter 1 in Grieve (2022).
(2) Estimating unit information standard deviation using sample sizes
When effect sizes are on a non-standardized scale (measure = "GEN") or use a
standardized effect size without known UISD, the UISD can be estimated from
sample sizes (ni) and standard errors (sei) following Equation 6 in
Röver et al. (2021). The estimated UISD is then used to
scale the default prior distributions as described in section (1).
Note that the known UISD for standardized effect size measures (section (1)) is
used if available, even when ni is provided.
(3) Manually setting unit information standard deviation
Alternatively, the UISD can be specified directly via the prior_unit_information_sd
argument. This is useful when the appropriate scale for prior distributions is known
a priori or when multiple analyses are to be performed on subsets of the same data
(re-estimating UISD on different subsets of the data can lead to slightly different
prior distributions for different subsets; see estimate_unit_information_sd()).
The specified prior_unit_information_sd is then used to scale the default prior
distributions as described in section (1).
Note that the manually specified prior_unit_information_sd takes precedence over
the estimated UISD from ni (section (2)) and the known UISD from measure
(section (1)). It cannot be combined with prior_informed_field.
(4) Specifying informed empirical prior distributions
Informed prior distributions can be specified via the prior_informed_field and
prior_informed_subfield arguments. Currently, only prior_informed_field = "medicine"
with subfields defined in BayesTools::prior_informed_medicine_names is supported,
which uses empirically derived prior distributions from medical meta-analyses as described in
Bartoš et al. (2021) and
Bartoš et al. (2023).
When prior_informed_field = "medicine", the default prior_informed_subfield is
"Cochrane" (i.e., using the whole CDSR database as a reference). The informed
prior distributions are available for the following effect size measures:
"SMD": | standardized mean difference |
"OR": | log odds ratio |
"RR": | log risk ratio |
"RD": | risk difference |
"HR": | log hazard ratio |
Note that informed prior distributions are only available for the effect size (\mu)
and heterogeneity (\tau) parameters. For effect moderation (prior_mods), the
informed effect prior is scaled by a factor of RoBMA.get_option("default_informed_priors.mods").
For heterogeneity moderation (prior_scale), a normal prior with standard deviation
specified by RoBMA.get_option("default_informed_priors.scale") is used.
(5) Fully custom prior distributions
Prior distributions can be fully customized by directly specifying the prior_effect,
prior_heterogeneity, prior_mods, prior_scale, and prior_heterogeneity_allocation
arguments. These should be prior distribution objects created via BayesTools::prior()
or related functions (e.g., prior_factor()).
Rescaling prior distributions
The rescale_priors argument allows rescaling supported prior distributions by a
multiplicative factor. For example, rescale_priors = 2 doubles the standard
deviations/scales of normal, Cauchy, t, and inverse-gamma prior distributions,
making them more diffuse. Point and none priors are unchanged.
Handling of continuous and factor predictors
When standardize_continuous_predictors = TRUE, continuous moderator and
scale predictors are internally standardized before fitting. Reported
summaries are transformed back to the original predictor scale by default;
use standardized_coefficients = TRUE in summary() or related methods to
inspect coefficients on the standardized scale.
Factor predictors use the contrast specified by
set_contrast_factor_predictors. The default "treatment" follows standard
treatment coding. Model-averaging functions default to "meandif" so
inclusion priors for factor levels are centered on deviations from the grand
mean.
Value
A fitted object of class c("brma.norm", "brma"). The object
contains checked data, checked priors, the JAGS fit, cached summary,
and cached coefficients. If the corresponding package options are enabled,
it can also contain cached LOO, WAIC, or marginal likelihood results. The
advanced internal only_data = TRUE and only_priors = TRUE paths return
partially constructed objects.
References
Bartoš F, Gronau QF, Timmers B, Otte WM, Ly A, Wagenmakers E (2021).
“Bayesian model-averaged meta-analysis in medicine.”
Statistics in Medicine, 40(30), 6743–6761.
doi:10.1002/sim.9170.
Bartoš F, Otte WM, Gronau QF, Timmers B, Ly A, Wagenmakers E (2023).
“Empirical prior distributions for Bayesian meta-analyses of binary and time-to-event outcomes.”
doi:10.48550/arXiv.2306.11468.
Preprint available at https://doi.org/10.48550/arXiv.2306.11468.
Grieve AP (2022).
Hybrid frequentist/Bayesian power and Bayesian power in planning clinical trials.
Chapman and Hall/CRC.
Röver C, Bender R, Dias S, Schmid CH, Schmidli H, Sturtz S, Weber S, Friede T (2021).
“On weakly informative prior distributions for the heterogeneity parameter in Bayesian random-effects meta-analysis.”
Research Synthesis Methods, 12(4), 448–474.
doi:10.1002/jrsm.1475.
Spiegelhalter DJ, Abrams KR, Myles JP (2004).
Bayesian approaches to clinical trials and health-care evaluation.
John Wiley and Sons.
doi:10.1002/0470092602.
See Also
RoBMA(), BMA(), brma.glmm(), summary.brma(),
plot.brma(), predict.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(
yi = yi,
vi = vi,
mods = ~ ablat + year,
data = dat,
measure = "RR",
seed = 1,
silent = TRUE
)
summary(fit)
predict(fit, type = "terms")
}
## End(Not run)
Bayesian Generalized Meta-Analysis
Description
Function for fitting random-effects, meta-regression, multilevel, and location-scale meta-analytic models directly to either binary or count data.
Usage
brma.glmm(
ai,
bi,
ci,
di,
n1i,
n2i,
x1i,
x2i,
t1i,
t2i,
weights,
mods,
scale,
cluster,
data,
slab,
subset,
measure = "OR",
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_heterogeneity_allocation,
prior_baserate,
prior_lograte,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
...
)
Arguments
ai |
a vector of the number of events in the treatment or experimental group for binomial GLMM models. |
bi |
a vector of the number of non-events in the treatment or experimental group for binomial GLMM models. |
ci |
a vector of the number of events in the control group for binomial GLMM models. |
di |
a vector of the number of non-events in the control group for binomial GLMM models. |
n1i |
a vector of the sample size in the treatment or experimental
group. If omitted for binomial GLMMs, it is computed as |
n2i |
a vector of the sample size in the control group. If omitted for
binomial GLMMs, it is computed as |
x1i |
a vector of the number of events in the treatment/experimental group (for Poisson data). |
x2i |
a vector of the number of events in the control group (for Poisson data). |
t1i |
a vector of the person-time in the treatment/experimental group. |
t2i |
a vector of the person-time in the control group. |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_heterogeneity_allocation |
prior distribution for the fraction of
heterogeneity allocated to the cluster-level component in multilevel models
( |
prior_baserate |
prior distribution for the estimate-specific midpoint
base-rate probability in binomial GLMM models ( |
prior_lograte |
prior distribution for the estimate-specific midpoint
log-rate in Poisson GLMM models ( |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
Details
Model for odds ratios (measure = "OR") corresponds to Model 4 described in
Jackson et al. (2018).
logit(pi[i]) is the study-specific midpoint of the two arm logits.
prior_baserate defines the estimate-specific prior distribution on pi[i].
Model for incidence rate ratios (measure = "IRR") corresponds to
Bagos and Nikolopoulos (2009).
phi[i] is the study-specific midpoint of the two arm log incidence rates.
prior_lograte defines the estimate-specific prior distribution on phi[i].
If unspecified, a unit-information prior is based on the data and used
independently for each estimate.
When weights are supplied, they are treated as likelihood weights on the
paired two-arm study contribution.
Value
A fitted object of class c("brma.glmm", "brma"). The object
contains checked data, checked priors, the JAGS fit, cached summary,
and cached coefficients. If the corresponding package options are enabled,
it can also contain cached LOO, WAIC, or marginal likelihood results.
See Also
brma(), BMA.glmm(), summary.brma(), predict.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
fit <- brma.glmm(
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
mods = ~ alloc,
data = dat.bcg,
measure = "OR",
seed = 1,
silent = TRUE
)
summary(fit)
}
## End(Not run)
Bayesian Meta-Analysis With Known Sampling Covariance
Description
Fits normal-likelihood Bayesian meta-analytic models with a
known working variance-covariance matrix V. The interface supports
location moderators, BayesTools random-effect formulas using
random-effect formula structure tags, and
brma.mv()-specific known-V backends.
Usage
brma.mv(
yi,
V,
ni,
mods,
scale,
random,
R = NULL,
Rscale = "cor",
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
known_v_parameterization = "auto",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
...,
vi = NULL,
sei = NULL
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
V |
a known working variance-covariance matrix, a list of block
variance-covariance matrices, or an exact diagonal-plus-factor declaration
created by |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
random |
Optional BayesTools random-effect formula or list of formulas.
Omission or |
R |
optional known random-effect group covariance/correlation matrix,
or a named list of matrices. Matrix row and column names identify grouping
levels. This is distinct from the known sampling covariance |
Rscale |
scaling applied to each supplied |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
known_v_parameterization |
known- |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
Details
brma.mv() represents known sampling dependence through a latent D + BB'
decomposition of V (known_v_parameterization = "latent"), through an
eigen-rotated likelihood (known_v_parameterization = "whitened"), or
through an exact native block multivariate-normal likelihood
(known_v_parameterization = "block_mvn"). The default
known_v_parameterization = "auto" chooses the whitened backend whenever the
extra diagonal variance is scalar and no scale regression is present,
otherwise chooses block-MVN when the
largest dense covariance block is at or below the configured feasibility
threshold, and falls back to the latent backend for large blocks. The automatic
block-MVN threshold defaults to 128 rows per covariance block and can be
changed with options(RoBMA.known_v_block_mvn_max_block_size = value), where
value is a positive integer or Inf. Correlated V with scale regression
cannot use "whitened"; request "block_mvn" explicitly if an automatic
latent decomposition is unavailable for a nearly singular block.
Covariance inputs retain their symmetric representation. Numerical
positive-semidefinite checks use standardized correlations so small marginal
variances are not mistaken for null directions. At a numerically singular
boundary, the computational factor uses the existing eigensolver roundoff
tolerance; sampling, whitening, and conditional calculations share its
support. This numerical rule is separate from the selection model's
condition/integrate source choices. Exact rank-one dependency
blocks are represented by one latent sampling factor, including when another
backend was requested, so correlations of one and any separate positive
diagonal variance retain their mathematical structure.
Singular positive-semidefinite V matrices are supported only when
integrated conditional variance is structurally positive on every retained
null direction. This can come from strictly positive heterogeneity or a
supported marginalized random-effect variance. The check is performed after
formulas and priors are compiled. Sampled random effects change the
conditional mean and therefore do not regularize the likelihood covariance.
For the block-MVN backend, a fixed point regularizer must also be large
enough to make each block numerically positive definite at double precision;
ineffective fixed values fail during preflight rather than inside JAGS.
The latent known-V backend is unavailable for other singular V matrices;
use "auto", "whitened", or "block_mvn". Unsupported configurations
fail before fitting rather than invoking a degenerate-normal likelihood.
As a convenience for diagonal known-V inputs, brma.mv() also accepts
named vi or sei arguments when V is omitted; these are converted to
diag(vi) or diag(sei^2). Do not supply V together with vi or sei.
Omitted or NULL random declares no random-effects structure. No implicit
tau or heterogeneity mixture is added. Do not supply prior_heterogeneity
or prior_heterogeneity_null without random, even as NULL or a zero prior;
omit these irrelevant arguments instead. Scale formulas also require an
explicit random structure. This rule applies to all .mv constructors;
specialized univariate models retain their usual implicit heterogeneity and
clustered tau/rho/I2 behavior.
The random argument uses BayesTools
random-effect formula structure tags.
Plain (expr | group) syntax creates an unstructured random-coefficient
block, and expr || group creates a diagonal block. Therefore
~ 1 | study, ~ 1 + x | study, and nested forms such as
~ 1 | study/effect are supported. The explicit us() / un(), diag(),
and id() tags use the same coefficient-formula semantics. The structured
cs() / hcs(), ar1() / ar() / har(), and car() tags instead own
their index basis; see the linked tag documentation before specifying factor
slopes or index variables.
BayesTools stores fully explicit canonical random-effect names of the form
(formula) owner: quantity(arguments). RoBMA uses their simplified display
aliases through RoBMA's meta-analytic naming map consistently in summaries,
plotting, density estimation, hypotheses, and posterior draws. A sole random
intercept drops its redundant argument, so a bare block is displayed and
accepted as tau, while an explicitly named block is study: tau; the
unique shorthand tau is also accepted. A non-intercept coefficient remains
explicit, for example study: tau(x). Bare formulas and
unnamed one-entry lists omit a redundant owner; explicitly named one-entry
lists retain it, and missing names in longer lists become component 1,
component 2, and so on. Allocation names include tau_total, tau_common,
and tau2_prop(study). BayesTools retains its general sd/var/cor
vocabulary internally; none of these public RoBMA names expose backend
coordinates.
The optional R argument supplies known covariance or correlation matrices
across random-effect grouping levels, following metafor::rma.mv() naming.
R is separate from the known sampling covariance V: V describes
sampling-error dependence between estimates, while R describes the
latent group-axis covariance of random intercepts. Current R support is
limited to random-intercept blocks. Rscale controls how each supplied
R matrix is scaled before fitting and accepts
"cor", "none", "cor0", "cov0", plus metafor-compatible aliases
TRUE/1 for "cor", FALSE/0 for "none", 2 for "cor0",
and 3 for "cov0".
In non-selection Gaussian models with random, shared sampled
random-effect blocks enter the conditional mean through BayesTools. A
supported one-to-one random-intercept block is automatically integrated into
the likelihood variance. Other terms remain sampled with their full
covariance. With a single top-level random component, scale
models the row-wise total random-effect SD consumed by that component. A
named list of scale formulas can instead target top-level random components
or concrete random-effect blocks. Block names and grouping labels are
accepted, and the terminal grouping variable is an alias for an unambiguous
nested block; for example, scale = list(esid = ~ x) targets the esid
block in random = ~ 1 | study / esid. Untargeted blocks retain their
ordinary SD priors. Component names can be ordinary text; RoBMA normalizes
them internally for JAGS. A single scale formula is rejected for multiple
top-level random components because the target is ambiguous. In model-
averaged models, block-specific scales inside one grouped component require
the blocks to be supplied as separately named random entries so their
inclusion gates remain well-defined.
When scale is a named list, prior_scale must either be omitted or use the
same named-list shape with one prior list per scale component, using the
same user-facing names. Post-fit scale predictions for random-formula
models keep these component scales separate rather than collapsing them into
one total \tau.
In non-selection Gaussian models, a supported random-intercept block that
maps one-to-one to estimates
is automatically compiled as a marginalized variance component
instead of sampled latent coefficients. This preserves estimate-level
heterogeneity semantics while keeping shared higher-level random effects
conditional. For known R, this automatic marginalization is available only
when BayesTools validates a one-column random-intercept block whose
Z K Z' row-space contribution is diagonal and one-to-one with the fitted
rows; RoBMA then adds the BayesTools-prepared row multiplier to the known-V
extra variance. Other known-R blocks remain sampled or are rejected by
BayesTools validation. Slopes and other unsupported variance forms remain
sampled. Multiple declared terms with one grouping level per estimate are
rejected, regardless of their coefficient basis or known group covariance.
The implementation intentionally omits the weights and cluster arguments
from metafor::rma.mv(). Use random for multilevel structures.
Estimate-unit log_lik(), add_loo(), add_waic(), residuals(), and
rstudent() are available for known-V models. Bridge-sampling marginal
likelihoods via add_marglik() are available for fitted single-model
known-V objects. rstandard() is available for known-V models at
supported estimate and marginal conditioning depths.
Value
A fitted object of class c("brma.mv", "brma.norm", "brma").
The advanced internal only_data = TRUE path returns checked data before
prior validation and random-effect marginalization decisions; use
only_priors = TRUE when inspecting the compiled random-effect structure.
Diagnostic target semantics
The main brma.mv() post-fit methods intentionally use different targets:
-
log_lik(unit = "estimate"),add_loo()/loo(),add_waic()/waic(), andrstudent()use estimate-unit log-score targets. When knownVinduces dependence, these contributions are Schur-complement conditionalsp(y_i \mid y_{-i}, \theta)within dependency blocks. They are existing-estimate diagnostics, not independent new-estimate prediction targets. Every local Gaussian random effect is integrated, so the target is the same whether the fitting parameterization sampled or marginalized the effect. When known random-effect covarianceRis supplied, the knownRmatrix and the fitted random-effect covariance enter the marginalZGZ'covariance of the Schur conditional through BayesTools' compiled random-effect metadata. -
dfbetas()andcovratio()use estimate-unit PSIS weights. With correlated knownV, their interpretation is parameter influence under conditional estimate deletion, not independent-study deletion. -
add_marglik()/bridge_sampler()uses the full fitted likelihood corresponding to the selected known-Vbackend. It does not use the estimate-wise conditional target from LOO/WAIC. During bridge evaluation, sampled Gaussian location random effects are integrated exactly asZGZ'while retaining every covariance parameter and prior; fitted diagonal marginalized blocks remain in the row variance. Selection likelihoods instead preserve the normalization boundary declared byselection_model(): retained contextual sources remain outside the normalizer and integrated sources enter the conditional covariance. -
hatvalues(), marginalrstandard(), andvif()use a marginal GLS covariance target based onV + ZGZ', where formula random effects are marginalized through the BayesTools covariance metadata. -
dffits()andcooks.distance()use fixed-location fitted-value influence targets. Cluster/block LOO is deferred forbrma.mv()because its deletion target is a joint dependency block, not an independent row.
Without random, the model estimates no heterogeneity. Explicit
random-formula models report component-specific standard deviation,
correlation and allocation summaries. A single homogeneous random component
uses the RoBMA names tau and tau2.
summary_heterogeneity(component = ...) describes component heterogeneity
over the observed design, whereas pooled_heterogeneity(component = ...)
evaluates absolute component heterogeneity at the average expanded random
design. Both report the fitted heterogeneity scale without fixed known-R
group covariance multipliers; row-specific scale prediction and covariance
consumers retain the full known R. General known-V models do not report
scalar I2/H2.
See Also
random_effect_formula_tags,
random_effect_prior_specification, brma(),
BMA.mv(), RoBMA.mv(), bPET.mv(), bPEESE.mv(), bselmodel.mv(),
summary.brma(), predict.brma()
Examples
## Not run:
V <- matrix(c(0.04, 0.01, 0.01, 0.09), 2, 2)
fit <- brma.mv(
yi = c(0.10, 0.20),
V = V,
measure = "GEN",
prior_unit_information_sd = 1,
seed = 1,
silent = TRUE
)
summary(fit)
## End(Not run)
Bayesian Selection Model
Description
Function for fitting random-effects, meta-regression, multilevel, and location-scale meta-analytic selection models.
Usage
bselmodel(
yi,
vi,
sei,
weights,
ni,
mods,
scale,
cluster,
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_heterogeneity_allocation,
prior_bias,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
effect_direction = "detect",
steps,
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
selection = BayesTools::selection_model(),
selection_control = set_selection_likelihood_control(),
...
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_heterogeneity_allocation |
prior distribution for the fraction of
heterogeneity allocated to the cluster-level component in multilevel models
( |
prior_bias |
selection-model bias prior, usually created by
|
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
effect_direction |
direction used by publication-bias adjustments.
|
steps |
numeric vector of one-sided p-value cut points for the
default selection model. If |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
selection |
specification created by |
selection_control |
numerical integration settings created by
|
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
Details
bselmodel() is a normal/effect-size selection-model constructor. Custom
prior_bias can be a weightfunction prior or a supported BayesTools
selection-kernel prior; p-hacking kernels are not supported in active RoBMA.
By default, the model conditions on contextual cluster effects and uses
the product of estimate weights. For independent rows conditional on these
effects, this gives the usual selected-normal likelihood with within-cluster
heterogeneity integrated. Use selection = selection_model(...) to choose
weight_rule = "best", which uses the weight at the smallest p-value in
each publication group. For "best", group identifies a data column;
when group = NULL, the specialized cluster argument supplies publication
groups, or an unclustered model uses one group per estimate. Product models
use neither input to define selection groups.
All conditioning choices use the same Gaussian source model. Conditioned
sources remain latent; their population distributions stay outside selection
normalization. Integrated sources may be reweighted by selection. With all
sources conditioned and positive weights, the weights cancel and the
observed law is the ordinary Gaussian model. See bselmodel.mv() for the
complete source and covariance contract.
Product normalizers factorize only for conditionally independent
rows. Dependent events use supported covariance-factor quadrature or fixed
randomized quasi-Monte Carlo integration with explicit error diagnostics.
Non-unit observation weights require
known_sampling_variance = "integrate" and independent product factors.
Unit weights are equivalent to omitting weights.
Value
A fitted object of class c("bselmodel", "brma") containing a
single Bayesian selection model fit.
See Also
publication_bias_prior_specification, RoBMA(), bPET(),
bPEESE(), summary.brma(), funnel.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bselmodel(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
steps = 0.025,
seed = 1,
silent = TRUE
)
summary(fit)
funnel(fit)
}
## End(Not run)
Bayesian Multivariate and Multilevel Selection Model
Description
Fits estimate-level Bayesian selection models with known sampling covariance and BayesTools random-effect formulas.
Usage
bselmodel.mv(
yi,
V,
ni,
mods,
scale,
random,
R = NULL,
Rscale = "cor",
data,
slab,
subset,
measure,
prior_effect,
prior_heterogeneity,
prior_mods,
prior_scale,
prior_bias,
standardize_continuous_predictors = TRUE,
set_contrast_factor_predictors = "treatment",
prior_unit_information_sd,
rescale_priors = 1,
prior_informed_field,
prior_informed_subfield,
effect_direction = "detect",
steps,
selection = BayesTools::selection_model(),
selection_control = set_selection_likelihood_control(),
known_v_parameterization = "auto",
sample = 5000,
burnin = 2000,
adapt = 500,
chains = 3,
thin = 1,
parallel = FALSE,
autofit = FALSE,
autofit_control = set_autofit_control(),
convergence_checks = set_convergence_checks(),
seed = NULL,
silent,
...,
vi = NULL,
sei = NULL
)
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
V |
a known working variance-covariance matrix, a list of block
variance-covariance matrices, or an exact diagonal-plus-factor declaration
created by |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
random |
Optional BayesTools random-effect formula or list of formulas.
Omission or |
R |
optional known random-effect group covariance/correlation matrix,
or a named list of matrices. Matrix row and column names identify grouping
levels. This is distinct from the known sampling covariance |
Rscale |
scaling applied to each supplied |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_bias |
selection-model bias prior, usually created by
|
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
effect_direction |
direction used by publication-bias adjustments.
|
steps |
numeric vector of one-sided p-value cut points for the
default selection model. If |
selection |
specification created by |
selection_control |
numerical integration settings created by
|
known_v_parameterization |
known- |
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
Details
Omitted or NULL random specifies a fixed-effect selection model with
no implicit heterogeneity. Both random-effect selection axes are then
inapplicable; the sampling-error selection axis still applies.
Heterogeneity priors and scale formulas require an explicit random structure.
bselmodel.mv() combines the selection-model interface of bselmodel() with
the known-covariance and random-formula model of brma.mv(). Each
weightfunction carries a selection_model() specifying whether estimate-level
random effects, other random effects, and the complete sampling error are
conditioned upon or integrated before selection normalization. The default
integrates estimate-level random effects and sampling error, conditions on
other random effects, and uses the product of estimate weights. The default
product rule needs no publication groups, so adding a three-level structure
requires only random = ~ 1 | study / esid.
weight_rule = "best" instead uses
the weight at the smallest actual p-value in the publication group.
With one cutoff and all three sources integrated, "best"
corresponds to the relaxed report-all rule of
van Aert et al. (in press): a favorable result
can select the publication vector, after which all measured outcomes are
reported. The other conditioning cells and multiple-cutoff best rules are
extensions of that specification.
Publication grouping is active only for weight_rule = "best". For grouped
multivariate models, specify it with
selection = selection_model(weight_rule = "best", group = study), or in
the selection model of an explicit weightfunction prior. Independent models
without a random structure can use singleton groups automatically. Covariance
matrices, including standard metafor::vcalc() results, and random-effect
grouping factors do not establish publication identities. With "product",
group is ignored: it is neither bound to a data column nor checked as a
publication partition. Integration follows the dependencies in V and the
integrated random effects, independently of publication grouping.
Sampling error is e \sim N(0,V). With positive sampling standard
errors it can equivalently be written as e = Sz, with
z \sim N(0,R) and V = SRS. Here S contains the original
sampling standard errors and R preserves their complete correlation
structure. Conditioning retains the entire realized vector e during
selection normalization. No residual sampling variation remains inside that
normalizer. Integration instead contributes the full V to candidate
variation. These choices apply equally to univariate, diagonal, and
correlated sampling covariance, including vi and sei inputs.
The covariance V remains authoritative. A diagonal-plus-factor input from
known_v_factor() can support more efficient calculations,
but equivalent representations define the same selection model with matching
source settings and, for "best", publication groups. Selection thresholds
always use the original sqrt(diag(V)). The same faster routes are reached
from an ordinary matrix whose dependency blocks are block constant on nested
partitions, such as compound symmetry or nested metafor::vcalc()
type/obs structures: that structure is recovered from the supplied
entries and reproduces them to working precision. It changes how the same
integral is evaluated, not which sampling sources are conditioned upon.
The likelihood and post-fit methods use the same resolved conditioning
model. known_v_parameterization and numerical integration settings cannot
change it. The estimate_random_effects setting controls estimate-level
true-effect variation. Shared covariance-factor and dense numerical paths use
explicit integration diagnostics.
The source settings define the reporting model. An optional comparison with
integrating retained contexts can be requested with
selection_sensitivity_diagnostics() or stored with
add_selection_sensitivity_diagnostics(). Fitting does not compute this
separate comparison automatically.
estimate_random_effects, other_random_effects, and
known_sampling_variance each accept "condition" or "integrate".
Both "product" and "best" support the resulting choices for supported
Gaussian sources, subject to the dependency restrictions below.
Retained contexts remain unknown and are estimated. Their population mixing laws stay outside the selection normalizer; integrating a context instead allows selection to reweight its mixing law. An absent context makes its two settings coincide. BayesTools identifies an estimate-level random term by a distinct grouping level for every retained estimate. At most one such term is allowed. Every other declared term is an other-level source, including terms with independent coefficient supports inside repeated groups. These roles do not split coefficient families or discard known group covariance; each choice applies to the complete declared random term.
With every outcome-generating source conditioned upon, candidate outcomes are deterministic within a retained context. If weights are positive almost surely, they cancel under conditional normalization: the observed law is the ordinary Gaussian model and carries no information about the selection weights. A zero acceptance probability on a positive-probability set of retained contexts makes this selection process invalid. It must not be handled by silently discarding those contexts. Ordinary population-level publication selection instead integrates all outcome-generating sources.
Product normalization retains all supported Gaussian dependencies. Best
weights require integrated dependencies to remain within each publication
group; an unsupported source is identified before
fitting. Conditioned sources may connect groups. Integrated candidate
covariance can be singular while the observed law remains nondegenerate
after averaging over retained sources. No residual noise is added to change
this boundary. Ensembles require a common conditioning cell across active
selection branches and a common publication partition across their "best"
branches only. Product branches impose no grouping requirements; an ensemble
without "best" accepts the default group = NULL. Bins, weight priors, and
supported weight rules may differ across branches.
Like the other brma.mv()-family constructors, bselmodel.mv() does not
accept observation weights.
Joint likelihoods, single-model bridge evidence, conditional-density
estimation, selected prediction, latent summaries, and z-plots use this
resolved model. Estimate-unit LOO, WAIC, and LOO-PIT integrate deleted
outcomes within the original publication event. Their conditional row scores
must not be summed and interpreted as a joint group likelihood. Cluster or
block deletion remains unavailable for arbitrary brma.mv() random formulas.
Product-space ensembles do not provide bridge marginal likelihoods.
With conditioned sampling, estimate deletion integrates the deleted sampling
error conditional on the retained sampling errors of the remaining estimates.
Marginal selected predictions draw new retained contexts from their original
mixing laws before drawing selected outcomes and reconstructing latent true
effects. At estimate depth, latent predictions draw fitted true effects;
blup() and fitted.brma() instead return conditional means. Response
prediction at estimate depth describes a new reporting event around fitted
truth, with new sampling error. Prediction's conditioning_depth is a
separate choice from the selection-model source settings.
Cluster depth is available only for the
specialized cluster interface. Known-covariance latent and response
predictions with newdata require V_new and, for "best", the resolved
publication-group reference; cross-covariance with fitted outcomes and
non-marginal newdata are unavailable. See predict.brma() for prediction
targets and labels.
When the complete sampling error is conditioned upon, total fitted truth
equals the observed estimate minus its fitted sampling error. Conditional
means and estimate-depth latent draws then coincide within each posterior
draw; uncertainty remains across posterior draws. Blockwise ranef() retains
its conditional-mean target for each random-effect block.
Partial-vector calculations retain the full selection event. Densities need a nondegenerate observed Gaussian law, except for supported one-coordinate projections of explicitly declared rank-one sources. Multicoordinate singular Lebesgue densities and general singular conditional latent posteriors are unavailable; zero integrated true-effect covariance gives deterministic latent effects. No general public multivariate CDF is provided. LOO-PIT and z-plots use their respective deletion and marginal projection targets.
Value
A fitted object of class
c("bselmodel.mv", "bselmodel", "brma.mv", "brma.norm", "brma").
References
van Aert RCM, Riley R, Jackson D (in press). “Correcting for publication bias in multivariate and multilevel meta-analysis: A multivariate step function selection model approach.” Psychological Methods. doi:10.31234/osf.io/rk4mn_v1.
See Also
bselmodel(), brma.mv(), set_selection_likelihood_control(),
summary.brma()
Examples
## Not run:
dat <- data.frame(yi = c(0.10, 0.20))
V <- matrix(c(0.04, 0.01, 0.01, 0.09), 2, 2)
fit <- bselmodel.mv(
yi = yi,
V = V,
data = dat,
measure = "GEN",
seed = 1,
silent = TRUE
)
summary(fit)
## End(Not run)
Check LOO Diagnostics for brma Objects
Description
Check Pareto k diagnostics for a brma model object and warn if any values are high.
Usage
## S3 method for class 'brma'
check_loo(object, unit = "estimate", ...)
Arguments
object |
a brma model object. |
unit |
output/deletion unit. See |
... |
currently unused. |
Details
LOO must first be computed with
object <- add_loo(object, unit = unit). With S posterior draws
in the stored LOO result, the method warns when any Pareto k diagnostic
is greater than \min(1 - 1 / \log_{10}(S), 0.7). The warning gives
that cutoff and the affected target indices.
Value
NULL (throws warning if diagnostics are unreliable).
Extract Model Coefficients for brma Objects
Description
Extract model coefficients (posterior means) from a fitted brma object.
Usage
## S3 method for class 'brma'
coef(object, ...)
Arguments
object |
a fitted brma object |
... |
additional arguments (currently ignored) |
Value
A named numeric vector of posterior mean coefficients.
See Also
BayesTools Contrast Matrices
Description
BayesTools provides several contrast matrix functions for Bayesian factor analysis. These functions create different types of contrast matrices that can be used with factor variables in Bayesian models.
Usage
contr.orthonormal(n, contrasts = TRUE)
contr.meandif(n, contrasts = TRUE)
contr.independent(n, contrasts = TRUE)
Arguments
n |
a vector of levels for a factor, or the number of levels |
contrasts |
logical indicating whether contrasts should be computed |
Details
The package includes the following contrast functions:
contr.orthonormalReturn a matrix of orthonormal contrasts: a normalised Helmert basis, whose columns have unit length and sum to zero and which is identical on every platform. Any orthonormal basis of the centred space implies the same exchangeable prior on the factor level effects under a spherical prior on the coefficients, which corresponds to the description by Rouder et al. (2012). Returns a matrix with n rows and k columns, with k = n - 1 if
contrasts = TRUEand k = n ifcontrasts = FALSE.contr.meandifReturn a matrix of mean difference contrasts. This is an adjustment to the
contr.orthonormalthat ascertains that the prior distributions on difference between the grand mean and factor level are identical independent of the number of factor levels (which does not hold for the orthonormal contrast). Furthermore, the contrast is re-scaled so the specified prior distribution exactly corresponds to the prior distribution on difference between each factor level and the grand mean – this is approximately twice the scale ofcontr.orthonormal. Returns a matrix with n rows and k columns, with k = n - 1 ifcontrasts = TRUEand k = n ifcontrasts = FALSE.contr.independentReturn a matrix of independent contrasts – a level for each term. Returns a matrix with n rows and k columns, with k = n if
contrasts = TRUEand k = n ifcontrasts = FALSE.
References
Rouder JN, Morey RD, Speckman PL, Province JM (2012). “Default Bayes factors for ANOVA designs.” Journal of Mathematical Psychology, 56(5), 356–374. doi:10.1016/j.jmp.2012.08.001.
Examples
# Orthonormal contrasts
contr.orthonormal(c(1, 2))
contr.orthonormal(c(1, 2, 3))
# Mean difference contrasts
contr.meandif(c(1, 2))
contr.meandif(c(1, 2, 3))
# Independent contrasts
contr.independent(c(1, 2))
contr.independent(c(1, 2, 3))
Cook's Distance for brma Objects
Description
Computes Cook's distance for a fitted brma object. Cook's distance measures the aggregate influence of each observation on the model coefficients.
Usage
## S3 method for class 'brma'
cooks.distance(model, ...)
Arguments
model |
a fitted normal-outcome |
... |
additional arguments (currently ignored). |
Details
Cook's distance is computed as a PSIS leave-one-out deletion diagnostic. For
each observation i, normalized PSIS weights estimate the fitted values
under the leave-one-out posterior. The distance is the squared posterior
Mahalanobis distance between the full-data and leave-one-out fitted-value
vectors:
D_i = \Delta_i' V_\mu^+ \Delta_i
where \Delta_i = \hat{\mu} - \hat{\mu}_{(-i)}, V_\mu^+ is the
generalized inverse of the full-posterior fitted-value covariance. This uses
the unscaled meta-analytic convention of metafor and
Viechtbauer and Cheung (2010), without division by the
fixed-effect model rank. Values can differ from metafor because RoBMA
uses posterior moments and PSIS deletion rather than classical refits.
For brma.mv() known-V models, Cook's distance uses
estimate-unit PSIS weights. With correlated known-V, deletion is
conditional estimate deletion and the reported fitted-value target is the
fixed-location mean \mu = X\beta; sampled or marginalized random
effects are not included in the reported fitted value.
Selection brma.mv() influence is currently unavailable. The PSIS
fixed-location moments do not require the inverse marginal covariance used
by hatvalues().
Value
A numeric vector of Cook's distance values, one for each observation.
References
(Viechtbauer and Cheung 2010)
See Also
influence.brma, dffits.brma, hatvalues.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_loo(fit)
cooks.distance(fit)
}
## End(Not run)
COVRATIO for brma Objects
Description
Computes COVRATIO for a fitted brma object. COVRATIO measures
the change in the determinant of the covariance matrix of the estimates
when observation i is removed.
Usage
## S3 method for class 'brma'
covratio(model, type = "mods", component = NULL, parameter = NULL, ...)
Arguments
model |
a fitted brma object. |
type |
type of parameters to be summarized. Defaults to |
component |
optional parameter namespace. Use |
parameter |
semantic random-effect quantity used when
|
... |
additional arguments. The internal |
Details
COVRATIO is computed using importance sampling weights to approximate the
leave-one-out covariance matrices without refitting the model.
Estimate-unit LOO must first be computed with
model <- add_loo(model, unit = "estimate"), unless internal weights
are supplied.
COVRATIO_i = \frac{\det(Cov(\beta)_{-i})}{\det(Cov(\beta))}
Values > 1 indicate that the observation improves precision (decreases
variance), while values < 1 indicate that the observation decreases precision
(increases variance).
For brma.mv() objects, COVRATIO uses estimate-unit PSIS weights. With
correlated known-V data, this is influence under conditional estimate
deletion, not independent-study deletion.
A requested random-effect correlation must be defined in every posterior
draw. If either SD is zero in some draws, the complete influence request is
unavailable; explicitly select an everywhere-defined quantity with
component = "random" and parameter instead.
Parameters with zero posterior variance are excluded from the covariance
determinant and reported in a printed note when available. Ordered terms
retain their fitted totals and omit one share per metadata-declared Dirichlet
simplex. Aliases of a shared allocation source contribute its independent
coordinates only once. If no estimable
parameters remain, or if a full or LOO covariance determinant is zero or
non-finite after exclusion, COVRATIO is undefined and values are reported as
NaN.
Value
A named numeric vector of COVRATIO values, one for each observation.
See Also
influence.brma, dffits.brma, cooks.distance.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_loo(fit)
covratio(fit)
}
## End(Not run)
Input Data Specification
Description
Shared data-input arguments used by the RoBMA fitting functions.
Normal models use approximate effect-size estimates supplied through
yi with either vi or sei. GLMM models use the raw two-arm count
arguments for binomial (measure = "OR") or Poisson (measure = "IRR")
outcomes.
Arguments
yi |
a vector of effect sizes, or a formula with the effect size on the
left-hand side and location moderators on the right-hand side (for example
|
vi |
a vector of sampling variances. Either |
sei |
a vector of standard errors. Either |
V |
a known working variance-covariance matrix, a list of block
variance-covariance matrices, or an exact diagonal-plus-factor declaration
created by |
known_v_parameterization |
known- |
weights |
an optional vector of finite positive likelihood weights. For
normal/effect-size models, each weight powers the estimate likelihood. For
constructors with GLMM raw-count input, each weight powers the paired
two-arm likelihood for one study. An integer weight |
ni |
an optional vector of sample sizes. Used for |
mods |
an optional matrix, data.frame, or formula specifying
location moderators (meta-regressors). Formula input is evaluated in |
scale |
an optional matrix, data.frame, or formula specifying
scale predictors for location-scale models. Formula input is evaluated in
|
random |
an optional formula or list of formulas specifying
BayesTools random-effect terms for |
cluster |
an optional vector of cluster identifiers for multilevel meta-analysis. |
data |
an optional data frame containing the variables. |
slab |
an optional vector of study labels. |
subset |
an optional logical or numeric vector specifying a subset of
data to be used. Subsetting precedes missing-row removal; retained-row
outcome and predictor checks follow these steps. Type, shape, and existing
extraction checks can still reject malformed inputs before subsetting.
Row selection (by |
measure |
a character string specifying the effect size measure.
Normal/effect-size constructors require an explicit value and support
|
effect_direction |
direction used by publication-bias adjustments.
|
ai |
a vector of the number of events in the treatment or experimental group for binomial GLMM models. |
bi |
a vector of the number of non-events in the treatment or experimental group for binomial GLMM models. |
ci |
a vector of the number of events in the control group for binomial GLMM models. |
di |
a vector of the number of non-events in the control group for binomial GLMM models. |
n1i |
a vector of the sample size in the treatment or experimental
group. If omitted for binomial GLMMs, it is computed as |
n2i |
a vector of the sample size in the control group. If omitted for
binomial GLMMs, it is computed as |
x1i |
a vector of the number of events in the treatment/experimental group (for Poisson data). |
x2i |
a vector of the number of events in the control group (for Poisson data). |
t1i |
a vector of the person-time in the treatment/experimental group. |
t2i |
a vector of the person-time in the control group. |
Extract qCMDE/IWMDE Density Diagnostics
Description
Extracts the compact reliability diagnostics attached to a qCMDE/IWMDE hypothesis result. The diagnostics describe the posterior ordinate computation. They do not include uncertainty in the prior ordinate or, for IWMDE, uncertainty from estimating its conditional weight function.
Usage
density_diagnostics(object, ...)
Arguments
object |
an object returned by |
... |
unused. |
Details
Point ordinates evaluate one fixed posterior-row sample whose size is chosen
by samples before any ordinate contributions are computed. Precision,
effective-sample-size, and contribution-concentration diagnostics never
determine whether that finite estimate is returned. An unmet
target_relative_mcse produces a warning; increase samples or set it to
Inf to use every eligible row. The
table records the requested and achieved sample sizes, all_rows_used,
whether the precision target was met, and whether the ordinate passed the
independent numerical-stability gates. Finite row budgets use a reproducible
simple random sample
without replacement. For a purely continuous ordinate, relative_mcse and
ess describe the selected continuous posterior-row sequence. For a mixed
point/continuous ordinate evaluated on every active continuous row, they use
the full conditioned-chain sequence, with zero contributions for inactive
rows, and therefore include active-mass uncertainty and its covariance with
continuous contributions. With a subset of active rows,
active_branch_relative_mcse describes the selected active-row contribution
sequence and active_mass_relative_mcse comes from the complete binary
indicator chain. relative_mcse is their conservative worst-correlation
delta upper bound on the unconditional density scale. It is suitable as a
descriptive precision diagnostic but does not certify the unobserved
full-mixture covariance, so bf_grade_met remains false.
sampling_relative_mcse separately reports the finite-population
simple-random-sampling component conditional on the fitted rows
(sampling_uncertainty_type = "finite_population_srswor"). The sampling
design is exact, but the standard error is an estimate: the usual
without-replacement formula applied to the sample variance of the selected
contributions, and zero when every eligible row is used. It is not
added to the selected-row sequence MCSE, which already describes the actual
selected estimator sequence.
These fields concern the continuous density ordinate. At a location that is also a posterior atom, the atom probability remains a separate discrete mass and is never added to the density ordinate.
ordinate and log_ordinate describe the posterior density at the requested
point, not the model's marginal likelihood. log_ordinate is retained only
when actually computed; it is not reconstructed for older results.
numerical_status distinguishes finite, underflow, overflow,
arithmetic_failure, invalid_density, zero_without_log_evidence,
nonfinite, and not_computed. Underflow/overflow requires finite log
evidence and confirmation that exponentiating that log loses range. A zero
without this evidence is not classified as a mathematical zero. A small
density alone does not establish unreliability.
Failed requested points retain separate diagnostic records with a
failure_reason, including failures occurring before a final ordinate was
obtained. status = "unavailable" distinguishes these failures from a
finite positive ordinate rejected by accuracy diagnostics. Ordinary-scale
precision diagnostics lost to underflow/overflow are unavailable, not zero
error or proof of convergence. Retaining a log estimate does not authorize a
Bayes factor: the existing finite-positive ordinate requirement is unchanged.
Legacy tables remain inspectable with unknown new fields set to NA.
A hypothesis result without attached diagnostics, such as one whose point
ordinates were estimated with density_method = "KDE" or one without a
point hypothesis, stops with the class
RoBMA_density_diagnostics_unavailable.
Density ordinate, diagnostic-unavailable, plot, and construction
(RoBMA_density_construction_error) conditions share the
RoBMA_density_error parent while retaining their specific condition classes.
The reliability policy warns when relative MCSE is at least 5 percent, ESS is below 100, the largest contribution share is at least 20 percent, or fewer than 100 finite contributions remain. These same-sample diagnostics do not reject a finite fixed-design estimate. Their warning thresholds are returned as columns rather than being implicit. For a descriptive mixed density curve using the conservative partial-row bound, a finite ESS below the usual curve rejection threshold is retained as a warning when the quantitative mixture-scale MCSE checks pass.
qCMDE's full method diagnostics distinguish pilot_normalization_integral
from final_normalization_integral; IWMDE uses
support_grid_normalization_integral. This compact accessor reports the
relative difference of the final integral from the active mass as
normalization_relative_error. For qCMDE it is a bookkeeping check, not a
discretization error: rows normalized on the lattice are normalized by the
same trapezoid rule, on the same grid, that integrates them, so they sum to
the active mass up to roundoff by construction, and rows normalized in
closed form contribute their analytic mass within the range. The
discretization and truncation errors of the lattice normalizers are reported
by ordinate_relative_change, lattice_resolution_relative_error, and
truncation_ordinate_bound. The active
policy check is identified by stability_metric: qCMDE checks its posterior
ordinate error estimate (ordinate_error_estimate), whereas IWMDE checks
normalization mass. The qCMDE estimate adds three parts. ordinate_relative_change
is the ordinate's movement between the selected normalization grid and the
coarser nested grid over the same range. It estimates the discretization
error of the lattice normalizers; it is an estimate, not a bound, because a
row narrower than the lattice step can escape both grids alike. Rows whose
lattice normalization is under-resolved also contribute an ordinate-share
weighted resolution estimate (lattice_resolution_relative_error), using
the kernel width or nested-grid log curvature at each row's maximum.
This component and their sum are estimates, not rigorous bounds: a sharp
prior core can be narrower than its likelihood kernel. Rows whose
Gaussian likelihood kernel meets a normal prior are normalized by the
closed-form mass of their support when their evaluated values are those of
that closed form: their normalizer is the same on every grid, so they add no
discretization change, lattice-resolution component or truncation. truncation_ordinate_bound is
t / (1 - t) for the largest fraction t of any row's conditional
mass outside the normalization range (normalization_truncation): a row
normalizer missing that fraction overstates the row's density by at most
this relative amount. normalization_truncation_status states how t
is known: "exact" for rows whose Gaussian likelihood kernel meets a normal
prior, "bound" for a Gaussian kernel with another proper prior, and
"estimate" (from the exponential envelope of the tails at the range ends)
otherwise; it reports the weakest status among the rows. The range covers
every row's central normalization_prob interval, so t is at most
1 - normalization_prob (for estimated rows, as estimated once their
extension reaches its target) and truncation_ordinate_bound is at most
(1 - normalization_prob) / normalization_prob, about 0.1 percent at the
default 0.999. The extension of an estimated row stops at its limit (four
initial range widths per side and 40 passes), at a value the joint density
cannot evaluate, or for a tail that does not decay; the reported
normalization_truncation and truncation_ordinate_bound can then exceed
these values. Setting normalization_prob closer to 1 widens the range
and lowers the truncation; increasing normalization_points refines the
grid. The table also reports the stability and adaptive-quadrature
warning/rejection thresholds.
Ordered effects use normalized conditional-source contributions for both
requested methods. Regular exact offsets can use a positive total/share
block. The complete numerical ratio error must be at most 0.025 for every
evaluated row, separately from the MCMC precision diagnostics. The columns
internal_method, working_distribution, and normalization_basis identify
this computation while estimator retains the requested method.
ordered_error_status preserves its estimated error status. Block numerator
and denominator errors, maximum quadrature order/panel count, and actual
native normalizer node count are reported in the block_* columns. Exact
offsets classified as nonfinite or unsupported are excluded only from density curves;
explicit point requests retain their structural or precision refusal.
The ordered per-row limit of 0.025 is separate from the generic stability
warning/rejection thresholds reported in this table.
Source-normalization refusals have class RoBMA_ordered_normalization_error
and retain iwmde_ordered_normalization_error as a compatibility ancestor.
Their condition's proof field contains the numerical integration evidence.
When only some ordered evaluations lack certified contribution variation,
their MCMC error and ESS stay unavailable while other evaluations retain
their metrics. A printed table footnote reports the partial uncertainty
status and its reason; the original selected-row scope stays in its column.
Such curves fail the MCMC availability gate, and an affected point cannot
meet its precision target.
If every evaluation is affected, the full unavailable scope is retained.
A finite log MCSE whose absolute value underflows remains a separate
representation limitation.
Value
A data frame of class RoBMA_density_diagnostics, with one row per
computed or failed requested point ordinate. Columns identify the estimator, parameter, requested
and evaluated values, schema/source provenance, row counts, active mass,
relative MCSE, ESS, largest contribution share, finite terms, normalization,
truncation, and quadrature checks, the qCMDE pilot-gate columns (the nested
normalization grids have no refinement sequence to stop, so
pilot_gate_stopped is FALSE and pilot_bulk_ess is NA),
fixed-sampling state, policy thresholds, weight fallbacks, status, and
warnings.
The exact columns, in order, are schema_version, algorithm_version,
source_fingerprint, estimator, internal_method, working_distribution,
normalization_basis, ordered_error_status,
block_numerator_relative_error, block_denominator_relative_error,
block_max_order, block_max_panels, block_native_nodes, density_method,
parameter, level, requested_value, evaluation_value,
requested_samples, achieved_row_budget, eligible_rows, evaluated_rows,
finite_terms, active_mass, relative_mcse, active_branch_relative_mcse,
active_mass_relative_mcse, mixture_mcse_type, sampling_relative_mcse,
sampling_fraction, mcmc_uncertainty_scope, sampling_uncertainty_type,
ess, max_weight_share, normalization_relative_error, stability_metric,
stability_relative_error, ordinate_relative_change,
lattice_resolution_relative_error, normalization_truncation,
normalization_truncation_status, truncation_ordinate_bound,
quadrature_relative_change, pilot_gate_stopped, pilot_bulk_ess,
target_relative_mcse, stability_warning_threshold,
stability_rejection_threshold, quadrature_warning_threshold,
quadrature_rejection_threshold, warning_relative_mcse,
warning_min_finite_terms, warning_min_ess, warning_max_weight_share,
all_rows_used, target_met, precision_target_met, sampling_target_met,
bf_grade_met, n_weight_fallbacks, weight_fallback_reasons, status,
ordinate, log_ordinate, numerical_status, failure_reason, and
warnings.
See Also
Examples
## Not run:
result <- hypothesis(
fit,
hypothesis = "mu != 0 vs mu = 0"
)
density_diagnostics(result)
failed <- tryCatch(
hypothesis(
fit,
hypothesis = "mu != 0 vs mu = 0",
density_method = "IWMDE"
),
RoBMA_density_ordinate_error = identity
)
density_diagnostics(failed)
## End(Not run)
DFBETAS for brma Objects
Description
Computes DFBETAS (Difference in BETAS, standardized) for a fitted brma object. DFBETAS measures the influence of each observation on the estimated model coefficients. Positive values indicate that deleting the observation yields a smaller estimate, negative values indicate that deleting the observation yields a larger estimate.
Usage
## S3 method for class 'brma'
dfbetas(
model,
type = "mods",
standardized_coefficients = FALSE,
transform_factors = TRUE,
return_loo_estimates = FALSE,
component = NULL,
parameter = NULL,
...
)
Arguments
model |
a fitted brma object. |
type |
type of parameters to be summarized. Defaults to |
standardized_coefficients |
whether to show standardized meta-regression
and scale-regression coefficients. Defaults to |
transform_factors |
whether to transform factors to their original names.
Defaults to |
return_loo_estimates |
whether to return the leave-one-out coefficient
estimates used to compute DFBETAS instead of standardized DFBETAS values.
Defaults to |
component |
optional parameter namespace. Use |
parameter |
optional semantic random-effect quantity. When omitted with
|
... |
additional arguments (currently ignored). |
Details
This function computes DFBETAS values using the Leave-One-Out (LOO) approximation based on Pareto Smoothed Importance Sampling (PSIS) weights. Ideally, DFBETAS is defined as:
DFBETAS_{ij} = \frac{\hat{\beta}_j - \hat{\beta}_{j(-i)}}{SE(\hat{\beta}_{j(-i)})}
where \hat{\beta}_j is the estimate of the j-th coefficient using
the full data, \hat{\beta}_{j(-i)} is the estimate when observation i
is omitted, and SE(\hat{\beta}_{j(-i)}) is the standard error of the
coefficient when observation i is omitted.
In the Bayesian context using LOO approximation:
-
\hat{\beta}_{j(-i)}is estimated as the importance sampling weighted mean of the posterior samples, using PSIS weightsw_{is}. -
SE(\hat{\beta}_{j(-i)})is estimated as the importance sampling weighted standard deviation of the posterior samples.
This approximation allows computing influence statistics without refitting
the model K times, making it computationally efficient.
For brma.mv() objects, DFBETAS use estimate-unit PSIS weights. With
correlated known-V data, this is influence under conditional estimate
deletion, not independent-study deletion.
A requested random-effect correlation must be defined in every posterior
draw. If either SD is zero in some draws, the complete influence request is
unavailable; explicitly select an everywhere-defined quantity with
component = "random" and parameter instead.
For type = "bias", fixed identification parameters (e.g., the reference
\omega = 1 interval) can have zero LOO posterior standard deviation.
These parameters are retained in the output, but their DFBETAS values are
reported as NaN because the standardized diagnostic is undefined.
Note: This function requires that LOO-CV has been computed for the model
using add_loo.
Value
If return_loo_estimates = FALSE, a data frame with K rows
(observations) and P columns (parameters), containing DFBETAS values.
If return_loo_estimates = TRUE, returns the corresponding leave-one-out
coefficient estimates. Row names correspond to study labels (if available)
or indices.
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_loo(fit)
inf <- dfbetas(fit)
plot(inf[, 1], type = "h")
}
## End(Not run)
DFFITS for brma Objects
Description
Computes DFFITS (Difference in FITS, standardized) for a
fitted brma object. DFFITS measures how much the fitted value for observation
i changes if observation i is removed, standardized by the
estimated standard error of the fit.
Usage
## S3 method for class 'brma'
dffits(model, ...)
Arguments
model |
a fitted normal-outcome |
... |
additional arguments (currently ignored). |
Details
DFFITS values are computed as a PSIS leave-one-out deletion diagnostic. For
each observation i, the leave-one-out posterior mean fitted value at
that observation is estimated with normalized PSIS weights and compared to
the full-posterior fitted value:
DFFITS_i =
\frac{\hat{\mu}_i - \hat{\mu}_{i(-i)}}{SD_{(-i)}(\mu_i)}
This targets deletion influence on fitted values directly. It does not use
LOO-PIT residuals, which are predictive outlier diagnostics rather than
fitted-value deletion diagnostics.
For brma.mv() known-V models, DFFITS uses estimate-unit PSIS
weights. With correlated known-V, deletion is conditional estimate
deletion and the reported fitted-value target is the fixed-location mean
\mu = X\beta; sampled or marginalized random effects are not included
in the reported fitted value.
Estimate-unit LOO must first be computed with
model <- add_loo(model, unit = "estimate"). If the leave-one-out
posterior SD of a fitted value is zero, the corresponding DFFITS value
is returned as NA, without a separate explanatory note.
The diagnostic is available for normal outcomes without a weightfunction
component; selection brma.mv() influence is currently unavailable.
Fixed-location PSIS moments do not require the inverse marginal covariance
used by hatvalues().
Value
A named numeric vector of DFFITS values, one for each observation.
See Also
influence.brma, cooks.distance.brma, hatvalues.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_loo(fit)
dffits(fit)
}
## End(Not run)
Estimate Unit Information Standard Deviation
Description
Estimates the unit information standard deviation (UISD) from sample sizes and standard errors. The UISD is used to scale weakly informative prior distributions for meta-analytic parameters.
Usage
estimate_unit_information_sd(sei, ni)
Arguments
sei |
a non-empty complete numeric vector of finite strictly positive standard errors for each study. |
ni |
a complete numeric vector of finite strictly positive sample sizes for
each study, with the same length as |
Details
The unit information standard deviation is computed following Equation 6 in Röver et al. (2021):
\text{UISD} = \sqrt{\frac{\sum n_i}{\sum \text{se}_i^{-2}}}
where n_i is the sample size and \text{se}_i is the standard error
for each study.
This function is useful when you want to compute the UISD once and pass it
to multiple analyses via the prior_unit_information_sd argument in
brma() or related functions. This ensures consistent prior scaling
across analyses performed on different subsets of the same data.
Value
Returns a single numeric value representing the estimated unit information standard deviation.
References
Röver C, Bender R, Dias S, Schmid CH, Schmidli H, Sturtz S, Weber S, Friede T (2021). “On weakly informative prior distributions for the heterogeneity parameter in Bayesian random-effects meta-analysis.” Research Synthesis Methods, 12(4), 448–474. doi:10.1002/jrsm.1475.
Examples
# Example with simulated data
sei <- c(0.2, 0.3, 0.25, 0.15)
ni <- c(50, 30, 40, 80)
estimate_unit_information_sd(sei = sei, ni = ni)
Fitted Values for brma Objects
Description
Extract in-sample fitted values from a fitted brma
object.
Usage
## S3 method for class 'brma'
fitted(
object,
unit = "estimate",
conditioning_depth = "marginal",
component = "location",
bias_adjusted = FALSE,
output_measure = NULL,
transform = NULL,
conditional = FALSE,
...
)
Arguments
object |
a fitted brma object. |
unit |
output unit. Only |
conditioning_depth |
conditioning depth for location fitted values.
|
component |
fitted component to return. |
bias_adjusted |
whether location fitted values should adjust for
publication bias. Defaults to |
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
conditional |
whether to return fitted values from conditional posterior predictions for RoBMA product-space objects. |
... |
additional arguments. Currently only |
Details
This method is a compact adapter around predict.brma. It
summarizes posterior prediction draws by their column means and returns a
base numeric vector, matching the usual fitted contract.
Use predict() directly when posterior draws or intervals are needed.
The default conditioning_depth = "marginal" corresponds to
predict(object, type = "terms") and matches the usual fitted-value
convention for meta-regression. For normal models,
conditioning_depth = "estimate" corresponds to BLUP means for the
observed estimates.
For component = "all", conditioning_depth,
output_measure, and transform apply only to the
location component. The scale component always returns
fitted \tau_i values.
Value
A numeric vector of fitted values, or a named list with
location and scale components when component = "all".
See Also
predict.brma(), residuals.brma(), blup.brma()
Fitting specification
Description
The brma family of functions uses the following arguments to specify the
MCMC sampling and fitting settings.
Arguments
sample |
numeric. Number of MCMC samples to save. Defaults to |
burnin |
numeric. Number of burn-in iterations. Defaults to |
adapt |
numeric. Number of adaptation iterations. Defaults to |
chains |
numeric. Number of MCMC chains. Defaults to |
thin |
numeric. Thinning interval. Defaults to |
parallel |
logical. Whether to run MCMC chains in parallel. Defaults to |
autofit |
logical. Whether to automatically extend the MCMC chains if convergence is not met.
Defaults to |
autofit_control |
list of autofit control settings. See |
convergence_checks |
list of convergence check settings. See |
seed |
numeric. Random seed for reproducibility. Defaults to |
silent |
logical. Whether to suppress output. Constructors with no
explicit default use |
... |
additional advanced arguments. Fitting functions reject unused
arguments; currently recognized internal arguments include |
See Also
brma, set_autofit_control, set_convergence_checks
Forest Plot for brma Objects Using metafor
Description
metafor::forest() creates a forest plot for a fitted
brma object by adapting RoBMA results to metafor's public forest
plotting API. Study rows are drawn by
forest.default and the RoBMA pooled posterior
summary is added with
addpoly.default.
Usage
## S3 method for class 'brma'
forest(
x,
addfit = TRUE,
addpred = FALSE,
newdata = NULL,
predstyle = "line",
mlab = NULL,
row = -1,
level = 95,
bias_adjusted = TRUE,
conditional = FALSE,
as_data = FALSE,
predlim,
border,
constarea,
...
)
## S3 method for class 'metafor_forest.brma'
forest(
x,
addfit = TRUE,
predstyle = "line",
mlab = NULL,
row = -1,
predlim,
border,
constarea,
...
)
Arguments
x |
a fitted brma object or an object returned by
|
addfit |
logical; whether to add the RoBMA pooled-effect summary
polygon. Defaults to |
addpred |
logical; whether to add a posterior prediction interval for
one new true effect. Defaults to |
newdata |
optional one-row prediction design used when
|
predstyle |
character; prediction interval style passed to
|
mlab |
label for the summary row. Defaults to |
row |
numeric row position for the pooled-effect summary polygon.
Defaults to |
level |
credible/confidence level in percent, greater than 0 and less
than 100. A value below 1 is read as a proportion ( |
bias_adjusted |
logical; whether pooled and prediction summaries should
adjust for publication bias. Defaults to |
conditional |
logical; whether to return conditional posterior
summaries for RoBMA product-space objects. Defaults to |
as_data |
logical; if |
predlim |
argument passed to
|
border, constarea |
arguments passed to
|
... |
additional arguments passed to
|
Details
This method deliberately uses metafor's public vector-based forest plotting
API instead of constructing a fake metafor model object. The observed study
rows are shown as usual Wald intervals based on the supplied effect sizes
and standard errors. The model summary row uses the posterior mean and
credible interval from pooled_effect. When
addpred = TRUE without newdata, the displayed center, credible
interval, and marginal prediction interval use the average-design target returned by
pooled_effect. With explicit newdata, all three refer
to that one prediction row and the prediction interval uses
predict.brma with type = "estimate" and
conditioning_depth = "marginal". For
metafor's predstyle = "shade" and
predstyle = "dist", the adapter supplies the predictive density.
Without newdata it is the posterior predictive density, a normal
mixture over the posterior draws, smoothed by a normal kernel for display (a
kernel density estimate of predictive draws without their simulation
noise); the smoothing keeps point masses (draws without heterogeneity)
visible. With newdata it is a kernel density estimate
of the predictive draws from predict.brma. The displayed prediction-interval endpoints are
the quantiles reported by pooled_effect or
predict.brma.
Additional study-level columns can be added with metafor's ilab
interface. When supplied to as_metafor_forest() or to
metafor::forest(..., as_data = TRUE), those arguments are stored in
the adapter object's forest_args; presentation options such as
addfit, row, and predstyle are retained by
forest(..., as_data = TRUE) for later rendering. Explicit plot-time
arguments override stored defaults. When supplied to
metafor::forest() at plot time, they are forwarded directly.
Use as_metafor_forest() to prepare the adapter object without
requiring a metafor installation.
Value
Invisibly returns the object returned by
forest.default. If as_data = TRUE, returns a
metafor_forest.brma object.
See Also
as_metafor_forest(), pooled_effect(), predict.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(yi = yi, vi = vi, data = dat, measure = "RR")
metafor::forest(fit)
metafor::forest(fit, addpred = TRUE, atransf = exp)
count_columns <- as.matrix(dat[, c("tpos", "tneg", "cpos", "cneg")])
metafor::forest(
fit,
addpred = TRUE,
slab = paste(dat$author, dat$year),
ilab = count_columns,
ilab.lab = c("T+", "T-", "C+", "C-"),
ilab.xpos = c(-8.5, -7.5, -6.5, -5.5),
xlim = c(-10, 4),
atransf = exp
)
}
## End(Not run)
Frequentist-Style and Bayesian Funnel Plots for brma Objects
Description
funnel.brma creates fast plug-in funnel contours.
Location and bias parameters are fixed at their within-model posterior means;
heterogeneity uses the root mean square SD, \sqrt{E(\tau^2)}. For
model-averaged fits, complete joint models retain their posterior model
probabilities and their plug-in sampling CDFs are averaged before the
contours are inverted. This makes the ordinary normal-model construction
directly comparable to a conventional plug-in funnel such as
metafor::funnel(..., addtau2 = TRUE).
bfunnel.brma instead averages the sampling CDF over posterior draws
before inversion. It therefore incorporates continuous parameter uncertainty
as well as model uncertainty.
Usage
## S3 method for class 'brma'
funnel(
x,
residual,
type = "LOO-PIT",
unit = "estimate",
conditioning_depth = "marginal",
sampling_heterogeneity = TRUE,
sampling_bias = TRUE,
max_samples = 10000,
plot_type = "base",
...
)
bfunnel(x, ...)
## Default S3 method:
bfunnel(x, ...)
## S3 method for class 'brma'
bfunnel(
x,
sampling_heterogeneity = TRUE,
sampling_bias = TRUE,
max_samples = 10000,
plot_type = "base",
...
)
Arguments
x |
a fitted brma object |
residual |
whether to use residual mode. Defaults to not specified, which means the function automatically determines the mode:
|
type |
the type of residuals to use when in residual mode. Options are:
Only used when funnel is in residual mode. |
unit |
output unit for residual mode. Only |
conditioning_depth |
conditioning depth for non-LOO residual mode.
Options are |
sampling_heterogeneity |
whether heterogeneity should be incorporated
into the sampling distribution funnel. Defaults to |
sampling_bias |
whether publication bias should be incorporated into the
sampling distribution funnel. Defaults to |
max_samples |
maximum number of posterior draws used by
|
plot_type |
whether to use a base plot |
... |
additional graphical arguments to customize the plot appearance:
|
Details
The ordinary funnel() has outcome and residual modes. If
residual is not specified, outcomes are used only when the fitted
model is intercept-only and its marginal heterogeneity is identical across
studies. The latter check uses fitted row-marginal random-effect variances,
including complete ZGZ' contributions for brma.mv() random-
formula models. All other models use residual mode.
Outcome mode (intercept-only models with common heterogeneity):
Displays observed effect sizes on the x-axis and standard errors on the
y-axis. The reference line follows the center of the fitted sampling
distribution. When sampling_bias = FALSE, this center is the plug-in
mixture median (the pooled effect in a single model); when PET/PEESE bias
adjustment is incorporated, the center line can vary with the standard
error. The funnel region represents the central 95\
region of the plug-in sampling distribution, optionally incorporating
heterogeneity and publication bias. Location and bias parameters use posterior
means, and heterogeneity uses the square root of the posterior mean variance,
separately within every complete joint model. Integrated and conditioned
variance components are averaged on the variance scale. The resulting
model-specific CDFs are averaged with posterior model probabilities and only
then inverted; neither parameters nor contour endpoints are averaged across
models.
For normal models, these contours use the marginal response target:
heterogeneity represents newly realized latent effects and fitted study
effects are not retained.
For correlated known-V brma.mv() models, outcome-mode funnels
use the diagonal of V for Gaussian marginal contours. The contour
describes a new, independent estimate at each hypothetical standard error,
so the fitted rows' correlations do not enter it: under
weight_rule = "product" such an estimate forms its own dependency
block and its selected law is the scalar selected normal at that standard
error, mixed over the population law of any conditioned source. Nonconstant
joint selection under a best weight rule instead weighs an estimate against
the others of its publication; it requires a full publication design at each
hypothetical standard error and remains unavailable in the scalar contour
calculation. Conditioning every applicable selection source cancels positive
weights and therefore retains the Gaussian contours. The observed estimates'
own selected marginals inside a correlated block differ from this new-study
contour; use zplot() to display them at the fitted publication
designs.
Residual mode follows the fitted estimate-unit residual target.
bfunnel() is available only for intercept-only normal models with
common marginal heterogeneity. It has no residual mode: explicitly supplied
residual, type, unit, or conditioning_depth
arguments are refused. It averages the same sampling CDF over
posterior draws and then inverts the averaged CDF. Thus it incorporates
posterior uncertainty in the effect, heterogeneity, PET/PEESE coefficients,
and selection parameters in addition to model uncertainty. For models
without a common outcome-scale target, use the default LOO-PIT residual
funnel from funnel().
Residual mode (models without a common outcome-scale target):
Displays residuals on the x-axis and standard errors on the
y-axis. The funnel region is bounded by the 0.025 and 0.975 normal quantiles
times the displayed standard error. It is a descriptive reference band, not
a posterior-predictive coverage interval. With type = "LOO-PIT", the
plotted x-coordinate is the PIT-normalized z value returned by
rstudent.brma multiplied by its LOO predictive standard
deviation. Consequently, each plotted x / se is exactly its LOO-PIT
z. This reduces to the ordinary raw deleted residual when the LOO
predictive distribution is normal and extends the same funnel geometry to
non-normal continuous predictive mixtures. With
type = "rstandard", the plotted values are internally standardized
residual companions from rstandard.brma. With
type = "outcome", these are raw outcome residuals and the band uses
sampling error only; it does not incorporate fitted heterogeneity.
The type argument controls how residuals are computed in residual
mode. See residuals.brma for details on each type.
The sampling_heterogeneity and sampling_bias arguments are
ignored in residual mode.
For GLMM models, outcome-mode observed effect sizes are computed from the raw
frequency data using formulas equivalent to metafor::escalc. Their
contours use the corresponding continuity-corrected effect-size estimates
and approximate standard errors in a normal reference calculation. The
default x-axis label and a warning identify this as a descriptive
approximation; it is not a coverage interval from the fitted binomial or
Poisson likelihood and does not use the prior-nuisance marginal GLMM response
target from predict(). Exact discrete-likelihood coverage cannot be
indexed by a scalar standard error alone because it also depends on arm
totals or exposures and nuisance rates.
LOO-PIT residual mode of GLMMs uses the descriptive normal approximation on
the effect-size scale of residuals.brma (the fitted predictive
distribution is discrete); the default x-axis label identifies it. The
sampling-error-only bands of the residual funnel are not exact diagnostics
for the fitted count likelihood.
Outcome-mode plot data carry the canonical RoBMA_target attribute.
Its reference_law identifies the independently published new-estimate
product-rule law; estimand separately records plug-in versus
posterior-predictive averaging. Declared source roles retain their provenance.
Value
If as_data = TRUE, funnel.brma and
bfunnel.brma return a list with the
data used for plotting, including the plotted points, funnel polygons,
plotting limits, labels, reference line, and outcome-funnel estimand. GLMM
outcome-mode data of funnel.brma also
contain an approximation record identifying the descriptive normal
effect-size approximation and stating that it is not fitted discrete-
likelihood coverage (bfunnel.brma is available only for normal
outcome models). Otherwise, it returns
NULL invisibly if plot_type = "base" or a ggplot object if
plot_type = "ggplot".
See Also
residuals.brma(), rstandard.brma(), rstudent.brma(),
predict.brma(), zplot.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(yi = yi, vi = vi, data = dat, measure = "RR")
funnel(fit)
bfunnel(fit)
funnel(fit, pch = 19, col = "blue", bg = "lightblue")
fit_reg <- brma(
yi = yi,
vi = vi,
mods = ~ ablat + year,
data = dat,
measure = "RR"
)
fit_reg <- add_loo(fit_reg)
funnel(fit_reg)
funnel(fit_reg, type = "outcome")
funnel_data <- funnel(fit, as_data = TRUE)
funnel(fit, plot_type = "ggplot")
}
## End(Not run)
Hat Values for brma Objects
Description
Computes hat values (leverages) from a fitted brma object. Returns posterior mean leverages, one for each observation.
Usage
## S3 method for class 'brma'
hatvalues(model, max_samples = Inf, ...)
Arguments
model |
a fitted brma object |
max_samples |
maximum posterior draws used for known- |
... |
additional arguments (currently ignored) |
Details
Hat values (leverages) measure the influence of each observation on the
fitted values. In a Bayesian meta-analysis, the random effects variance \tau^2
is uncertain, so the hat matrix depends on the posterior samples of \tau^2.
This function computes the diagonal elements of the hat matrix:
h_i = (X (X^T W X)^{-1} X^T W)_{ii}
where W is the fitted precision matrix. Without additional likelihood
weights it is the inverse marginal covariance; likelihood weights modify
estimation precision without redefining the original outcome covariance
used to standardize residuals.
The hat matrix is computed for each posterior draw and then averaged over
draws, matching the vector output shape used by metafor.
The members of a RoBMA() ensemble can differ in their PET and PEESE
terms; each draw then uses the design of the member it belongs to (the
location columns plus the PET column of PET members or the
PEESE column of PEESE members), and the reported leverage is the
posterior mean over all draws.
For known-V brma.mv() random-formula models, leverages use the
marginal GLS covariance V + ZGZ'.
This method is available only for normal outcome models without weightfunction selection.
For known-V models, the leverages require applying the inverse of the
marginal covariance. A covariance that is too ill-conditioned for that (a
reciprocal condition number of about 2e-10 or less in any posterior
draw used) is unavailable: the call stops with an error of class
RoBMA_known_v_precision_unavailable, whose parent class is
RoBMA_numerical_unavailable, instead of returning a rounded number.
The condition carries the draw positions (rows) and their
reciprocal_condition.
Value
A numeric vector of length K, one posterior mean leverage per
observation.
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(yi = yi, vi = vi, data = dat, measure = "RR")
hatvalues(fit)
}
## End(Not run)
Histogram of Z-Statistics
Description
Plots a histogram of observed z-values from the meta-analysis.
Usage
## S3 method for class 'zplot_brma'
hist(
x,
plot_type = "base",
from = -6,
to = 6,
by = 0.5,
length.out = NULL,
add = FALSE,
plot_thresholds = TRUE,
dots_thresholds = NULL,
dots_hist = NULL,
dots_all = NULL,
...
)
Arguments
x |
a zplot_brma object. |
plot_type |
graphics system: |
from, to |
z-value range for plotting. Defaults to |
by |
bin width. Defaults to 0.5. |
length.out |
number of bins (alternative to |
add |
whether to add to an existing base plot. Defaults to
|
plot_thresholds |
whether to show significance threshold lines.
Defaults to |
dots_thresholds |
graphical parameters for threshold lines (list). |
dots_hist |
graphical parameters for histogram (list). |
dots_all |
graphical parameters passed to all components (list). |
... |
additional graphical parameters, such as |
Details
Z-statistics are computed as effect size divided by standard error
(yi / sei). Histogram bins are adjusted to align with significance
thresholds when selection model priors are present. The bins cover
from to to; when by does not divide that range, the last
bin ends at to. xlim and ylim set the displayed axis
ranges without changing the bins. Standalone ggplot histograms scale
automatically to added layers unless ylim is supplied.
Value
NULL invisibly for base graphics, a ggplot2 object, or a data
frame with columns x, density, and breaks (bin widths)
when as_data = TRUE.
See Also
plot.zplot_brma(), lines.zplot_brma()
Hypothesis Bayes Factors
Description
Computes Bayes factors for scalar hypotheses written as
expressions, for example "mu = 0", "year > 0", or
"mu_alloc[alternate] > mu_alloc[random]".
Usage
hypothesis(object, ...)
## Default S3 method:
hypothesis(object, hypothesis, ...)
## S3 method for class 'brma'
hypothesis(
object,
hypothesis,
component = "auto",
standardized_coefficients = FALSE,
conditional = FALSE,
logBF = FALSE,
BF01 = FALSE,
seed = NULL,
density_method = "qCMDE",
density_control = NULL,
n_samples = 10000,
columns = "default",
...
)
## S3 method for class 'marginal_means.brma'
hypothesis(
object,
hypothesis,
parameter = NULL,
logBF = FALSE,
BF01 = FALSE,
seed = NULL,
density_method = NULL,
density_control = NULL,
columns = "default",
...
)
bf_hypothesis(object, ...)
BF_hypothesis(object, ...)
Arguments
object |
a fitted |
... |
additional arguments passed to methods. For fitted |
hypothesis |
character vector with scalar hypothesis statements. For
|
component |
parameter component. Defaults to |
standardized_coefficients |
whether moderator and scale coefficients
are tested on the standardized predictor scale. Defaults to |
conditional |
whether to use the conditional posterior for product-space
model-averaging objects. Defaults to |
logBF |
whether to display the Bayes factor on the log scale. |
BF01 |
whether to display the inverse Bayes factor. |
seed |
optional seed used by BayesTools for sampled prior quantities. |
density_method |
posterior density method. Defaults to The statements are planned and evaluated by the hypothesis engine of
BayesTools ( Statements that need to be restated, or an argument that needs to change,
stop with the class |
density_control |
named list of qCMDE/IWMDE tuning settings. Supported
entries are |
n_samples |
number of prior samples/grid points used by BayesTools for deterministic marginal prior densities. |
columns |
output columns passed to |
parameter |
optional marginal-means parameter/term used to disambiguate
the hypothesis expression. Without it, each statement is tested on the
marginal means of the parameter it names, so that separate statements may
refer to different parameters (for example
|
Details
For a continuous focal parameter \theta, nuisance parameters
\xi, and an unnormalized joint posterior kernel
q(\theta,\xi), qCMDE estimates the posterior ordinate as
\widehat{p}_{Q}(\theta^{*}\mid y)=\frac{1}{S}\sum_{i=1}^{S}
\frac{q(\theta^{*},\xi_{i})}{\int_{\Theta} q(t,\xi_{i})\,dt}.
Each row is therefore normalized over the focal-parameter support before the conditional densities are averaged. IWMDE instead uses
\widehat{p}_{I}(\theta^{*}\mid y)=\frac{1}{S}\sum_{i=1}^{S}
w(\theta_{i}\mid\xi_{i})\frac{q(\theta^{*},\xi_{i})}
{q(\theta_{i},\xi_{i})},
where w(\theta\mid\xi) is a normalized, fitted conditional weight.
For half-bounded targets, IWMDE fits the distance from the declared boundary
and normalizes a Normal weight over its central 95 percent positive-tail
interval, using the actual computed endpoints. A draw outside that compact
interval contributes zero while retaining its original row and chain. The
same compact family is used when conditional fitting is unavailable.
Compact focal support does not certify a finite joint second moment or
MCMC long-run variance; reported uncertainty is conditional on the fitted
proposal and does not include uncertainty from learning it on the same draws.
Spike-mixture and product-space results additionally retain the posterior
mass of the continuous active branch. These estimators build on conditional
marginal density estimation and importance-weighted marginal density
estimation (Gelfand et al. 1992; Chen 1994).
qCMDE is the preferred likelihood-aware method when it is supported and its
additional numerical normalization cost is acceptable. IWMDE can be faster,
but is more sensitive to the adequacy and concentration of its fitted
conditional weights. The normal approximation is useful as a rough check for
near-normal interior ordinates; it is not a validation reference for skewed
tails, bounded parameters, or one-sided support boundaries.
Selected weightfunction models near zero cumulative ordered effects can take
more than 10 minutes with qCMDE or IWMDE.
qCMDE is the default for fitted brma objects. Use "KDE",
"normal", or "IWMDE" explicitly to select another route.
For binomial and Poisson GLMMs, the nuisance state includes the sampled
estimate-level heterogeneity effects and baserates or log-rates. Averaging
the normalized row-conditional focal densities over the posterior draws of
this nuisance state targets the marginal posterior density by an exact
identity; the estimate approximates that expectation with the posterior
draws and numerical normalization, subject to the reported diagnostics.
IWMDE is unavailable for GLMM density estimation because its
high-dimensional conditional weights did not meet bridge-sampling
certification. GLMM density curves and point-null hypotheses require qCMDE.
qCMDE and IWMDE evaluate one scale formula: they are unavailable for
brma.mv() models with component-specific scale formulas (a named
scale list, e.g. one scale formula per random component), whose
point-null hypotheses use density_method = "KDE".
For an unrestricted alternative against \theta=\theta_0, the
Savage-Dickey identity (Dickey 1971; Wagenmakers et al. 2010)
gives
BF_{10}=p(\theta_0\mid H_1)/p(\theta_0\mid y,H_1) only when the null
model's nuisance-parameter prior is the conditional prior induced by the
unrestricted model at \theta_0. Otherwise, fit the constrained model
separately and compare marginal likelihoods, for example by bridge sampling.
Marginal-means hypotheses are specified on the fitted
linear-predictor scale. Display transformations stored by
marginal_means() do not transform hypothesis constants. Single-model
hypotheses and model-averaged region hypotheses use averaged marginal draws.
Model-averaged point-null hypotheses use alternative-conditioned draws to
avoid null atoms in averaged marginals. For model-averaged objects,
hypotheses that mix point and region events, and point hypotheses on more
than one marginal mean (several levels of a factor, or levels and scalar
marginal means of one parameter or of several), are not supported.
Separate region statements may refer to different parameters, while each
statement refers to the marginal means of one parameter.
Single-model hypotheses use one common averaged posterior and may combine
these events. Point hypotheses require the exact prior ordinate that
BayesTools attaches to the marginal mean, as for fitted objects.
Value
A BayesTools_hypothesis_BF BayesTools table.
References
Chen M (1994).
“Importance-weighted marginal Bayesian posterior density estimation.”
Journal of the American Statistical Association, 89(427), 818–824.
doi:10.1080/01621459.1994.10476815.
Dickey JM (1971).
“The weighted likelihood ratio, linear hypotheses on normal location parameters.”
The Annals of Mathematical Statistics, 204–223.
doi:10.1214/aoms/1177693507.
Gelfand AE, Smith AF, Lee T (1992).
“Bayesian analysis of constrained parameter and truncated data problems using Gibbs sampling.”
Journal of the American Statistical Association, 87(418), 523–532.
doi:10.1080/01621459.1992.10475235.
Wagenmakers E, Lodewyckx T, Kuriyal H, Grasman R (2010).
“Bayesian hypothesis testing for psychologists: A tutorial on the Savage–Dickey method.”
Cognitive Psychology, 60(3), 158–189.
doi:10.1016/j.cogpsych.2009.12.001.
See Also
density_diagnostics(), marginal_means(), plot.brma(),
bridge_sampler.brma()
Examples
## Not run:
fit <- brma(
yi = c(0.12, 0.20, 0.05, 0.33, 0.18),
sei = c(0.10, 0.12, 0.09, 0.15, 0.11),
measure = "GEN"
)
# Average-effect hypotheses
hypothesis(fit, "mu != 0 vs mu = 0")
hypothesis(fit, "mu > 0 vs mu = 0")
hypothesis(fit, "mu > 0 vs mu < 0")
# Heterogeneity hypothesis
hypothesis(fit, "tau = 0 vs tau > 0", component = "scale")
dat <- data.frame(
yi = c(0.12, 0.20, 0.05, 0.33, 0.18, 0.41),
sei = c(0.10, 0.12, 0.09, 0.15, 0.11, 0.14),
group = factor(c("A", "A", "A", "B", "B", "B"))
)
fit_mod <- brma(
yi = yi,
sei = sei,
mods = ~ group,
data = dat,
measure = "GEN"
)
# Marginal-mean hypothesis for a factor level
emm <- marginal_means(fit_mod, density_method = "qCMDE")
hypothesis(emm, "group[B] > 0 vs group[B] = 0")
## End(Not run)
Measure Influence for brma Objects
Description
Computes DFFITS, Cook's distance, COVRATIO, and other influence diagnostics for a fitted brma object.
Usage
## S3 method for class 'brma'
influence(model, ...)
Arguments
model |
a fitted brma object. |
... |
additional arguments (currently ignored). |
Details
The hat column uses the design of each draw's member for ensembles
whose members differ in their PET and PEESE terms, as described in
hatvalues.brma.
Selection brma.mv() models are currently unavailable through this
aggregate diagnostic. Standalone DFFITS and Cook's distance are available
for normal outcomes without a weightfunction component.
For known-V models, the hat values require applying the inverse of
the marginal covariance. DFFITS and Cook's distance use PSIS fixed-location
moments and do not apply this inverse. A covariance that is too
ill-conditioned for that (a reciprocal condition number of about 2e-10
or less in any posterior draw used) is unavailable: the call stops with an
error of class RoBMA_known_v_precision_unavailable, whose parent class
is RoBMA_numerical_unavailable, instead of returning a rounded number.
The condition carries the draw positions (rows) and their
reciprocal_condition.
Value
An object of class "infl.brma", which corresponds to the
structure of metafor::influence objects. It is a list containing:
inf |
A data frame with columns: |
dfbs |
A data frame with DFBETAS values for the model coefficients. |
Undefined COVRATIO and coefficient DFBETAS values are reported as
NaN with an explanatory note. DFFITS returns NA when its
leave-one-out posterior fitted-value SD is zero, without a separate note.
For binomial and Poisson GLMMs the rstudent component is the
descriptive normal approximation of rstudent.brma (and the
DFFITS, Cook's distance, and hat columns are not available).
For brma.mv() objects, influence returns only components with
implemented estimate-unit targets. DFFITS and Cook's distance report
influence on fixed-location fitted values \mu = X\beta; tau.del
is currently deferred.
With correlated known-V data, the returned PSIS influence components
use conditional estimate deletion rather than independent-study deletion.
See Also
dffits.brma, cooks.distance.brma,
covratio.brma, dfbetas.brma, hatvalues.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
fit <- add_loo(fit)
inf <- influence(fit)
print(inf)
}
## End(Not run)
Interpret brma Results
Description
Creates a concise textual interpretation of fitted RoBMA
brma objects.
Usage
interpret(object, ...)
## Default S3 method:
interpret(object, ...)
## S3 method for class 'brma'
interpret(
object,
output_measure = NULL,
transform = NULL,
conditional = FALSE,
scope = "core",
probs = c(0.025, 0.975),
central = NULL,
priors = FALSE,
digits = 3,
...
)
## S3 method for class 'interpret.brma'
print(x, ...)
Arguments
object |
a fitted model object. |
... |
additional arguments passed to methods. The |
output_measure |
optional effect-size measure used for the pooled
effect only. Supported conversion targets include |
transform |
optional display transformation. |
conditional |
whether to summarize conditional estimates for RoBMA
product-space objects. Defaults to |
scope |
character vector specifying sections to include. Use
|
probs |
two quantiles used for credible intervals. Defaults to
|
central |
whether estimates are described by posterior mean or median.
Defaults to |
priors |
whether to print prior distributions after the interpretation.
Defaults to |
digits |
number of digits after the decimal point. |
x |
an |
Value
A character vector with class "interpret.brma". The
normalized BayesTools interpretation records are stored in the
"records" attribute; the brma method also stores
"scope", "conditional", and optionally "priors".
Declare a diagonal-plus-factor sampling covariance
Description
Constructs an exact known sampling covariance representation
V = \mathrm{diag}(d) + U U^\mathsf{T}.
The supplied diagonal and loading matrix define V; no numerical rank is
inferred from a materialized covariance matrix. This representation permits
likelihood implementations to use the declared factor dimension when that
route is supported. Gaussian and selection models retain the same target
as a conventional dense V input with the same source settings and, for
best-p-value selection, publication groups.
With selection_model(known_sampling_variance = "condition"), the declared
covariance defines the complete retained sampling-error vector, including
both diagonal and factor variation. With known_sampling_variance = "integrate"
(the default), the full sampling error is integrated before selection
normalization. The diagonal-plus-factor split is a numerical representation;
it does not define which sampling sources are conditioned upon.
Ordinary covariance matrices, including results from metafor::vcalc(),
can also be supplied directly. Covariance inputs do not specify publication
groups. Only weight_rule = "best" uses publication groups; declare them
separately with selection_model(weight_rule = "best", group = ...).
The default product rule requires no publication grouping.
A declaration is not required to reach the factor routes. Dependency blocks
whose correlation is constant on nested partitions of their rows, which is
what compound symmetry and nested metafor::vcalc() type/obs
structures produce, are recognized from an ordinary matrix and represented
exactly as \mathrm{diag}(d) + U U^\mathsf{T}. Other blocks that are
exactly a diagonal plus a few loading columns, such as covariance from
overlapping samples, shared control arms, or partially shared raters, are
recovered by a rank search that stops at the first successful candidate,
the kernel rank cap, or the Ledermann bound. It finds the smallest rank
reached by that search, without certifying the minimum possible rank. The
recovered representation must reproduce the
supplied entries to working precision; blocks that do not, such as
autoregressive phi structures, keep the general route with the supplied
entries. V remains the stored covariance either way. Use
known_v_factor() to declare a factor that cannot be recovered from the
matrix, or to name its sources.
Matrix inputs use base R's numerical symmetry tolerance. Accepted matrices
are stored symmetrically by averaging corresponding off-diagonal entries,
leaving the supplied R object and its diagonal unchanged. Positive
semidefiniteness is judged from the standardized eigenvalues, with values
inside the eigensolver's roundoff envelope treated as zero. Exactly singular
designs are therefore accepted and factorized to their true rank, including
metafor::vcalc() output with rho = 1, whose diagonal and off-diagonal
reach working precision along different rounding paths. A singular
covariance still requires model structure covering its null space; see
brma.mv(). The stored covariance uses this symmetric representation and
retains input type and row mapping; it does not include a separate copy of
unequal input triangles.
Usage
known_v_factor(diagonal, loading)
Arguments
diagonal |
finite non-negative numeric vector |
loading |
finite numeric matrix |
Value
A RoBMA_known_v_factor object accepted as the V or V_new
argument of multivariate-model interfaces.
Add Zplot Density Lines
Description
Adds model-implied density lines to an existing zplot.
Usage
## S3 method for class 'zplot_brma'
lines(
x,
plot_type = "base",
probs = c(0.025, 0.975),
max_samples = if (inherits(x, "brma.mv")) 1000 else 10000,
plot_ci = TRUE,
extrapolate = FALSE,
from = -6,
to = 6,
by = 0.05,
length.out = NULL,
col = "black",
as_data = FALSE,
integration_control = x[["zplot"]][["data"]][["integration_control"]],
parallel = FALSE,
cores = min(4, RoBMA.get_option("max_cores")),
...
)
Arguments
x |
a zplot_brma object. |
plot_type |
graphics system: |
probs |
quantiles for credible intervals. Defaults to |
max_samples |
maximum posterior samples for density.
Defaults to 1000 for |
plot_ci |
whether to show credible interval bands. Defaults to |
extrapolate |
whether to remove bias adjustments. Defaults to |
from, to |
z-value range for density. Defaults to |
by |
step size for density points. Defaults to 0.05. |
length.out |
number of density points (alternative to |
col |
line color. Defaults to |
as_data |
whether to return data instead of plotting. Defaults to |
integration_control |
numerical integration settings created by
|
parallel |
whether to distribute multivariate selection-model density
calculations across local workers. Defaults to |
cores |
number of local workers when |
... |
additional graphical parameters. |
Details
The density uses the conditioning_depth stored by
as_zplot(). Recreate the zplot object to change the predictive target.
The line is the posterior mean of the density at each z value, and its
credible band (plot_ci = TRUE, or y_lCI and y_uCI of the
returned data) is formed by pointwise Harrell-Davis quantiles of the posterior
density draws at the probabilities probs, computed by
BayesTools::harrell_davis_quantile(). They estimate the same quantiles as the
empirical quantiles of the draws but smooth the kinks that the empirical
quantiles show along z. The bands remain pointwise, and, because every draw
contributes, they can differ visibly from the empirical quantiles when few
draws are used (max_samples below a few hundred). Near the edge of a
point mass in the draws (e.g., draws of models that fix the plotted quantity
in a model-averaged posterior) the band blends the point mass and the
remaining draws, and extreme probabilities (e.g., probs = c(.0005, .9995))
are not estimated more accurately than by the empirical quantiles; see
BayesTools::harrell_davis_quantile() for these caveats.
When extrapolate = FALSE, the density includes all bias adjustments
(PET/PEESE regression, selection weights) representing the fitted model.
When extrapolate = TRUE, bias adjustments are removed to show the
hypothetical distribution without publication bias. Multivariate models,
retained estimate-level or sampling-error sources, applicable integrated
contexts, and best-rule selection models use a
normalized pre-selection Gaussian reference. Released univariate product
targets retain inverse-weight scaling
and their extrapolated curve need not integrate to one.
Value
NULL invisibly for base graphics, ggplot2 layers for ggplot,
or a data frame with columns x, y, y_lCI, y_uCI
if as_data = TRUE.
See Also
plot.zplot_brma(), hist.zplot_brma()
Extract Log-Likelihood Matrix from brma Object
Description
Extract the pointwise log-likelihood matrix from a brma model
object. This is an S x K or S x G matrix where S is the number of posterior
samples, K is the number of estimates, and G is the number of clusters.
This method implements the S3
'logLik' generic for brma objects and returns the matrix of
pointwise log-likelihoods (one column per observation, one row per sample).
It returns the draws of log_lik, which documents the
targets of the columns; use log_lik() directly where the generic is
not required.
Usage
## S3 method for class 'brma'
logLik(object, unit = "estimate", ...)
Arguments
object |
a brma model object. |
unit |
output unit. See |
... |
currently unused. |
Details
The log-likelihood is computed for each observation at each posterior sample.
For binomial and Poisson models, each observation consists of a pair of
counts (ai/ci or x1i/x2i) that together define a single effect size estimate.
The matrix holds posterior draws, not a scalar maximized log-likelihood, so
AIC() and BIC() are not defined for brma objects (see
AIC.brma).
Value
An S x K or S x G matrix of log-likelihood values.
See Also
Extract Pointwise Log-Likelihood Draws
Description
Extract posterior pointwise log-likelihood draws from a fitted
brma object. The result is an S \times K or S \times G
matrix, where S is the number of posterior draws, K is the
number of estimates, and G is the number of clusters.
Usage
log_lik(object, ...)
## S3 method for class 'brma'
log_lik(object, unit = "estimate", ...)
Arguments
object |
a brma model object. |
... |
currently unused. |
unit |
output unit. See |
Details
This function returns posterior log-likelihood draws, not a scalar maximized
log-likelihood. The logLik.brma method returns the same matrix
for the stats::logLik() generic; AIC() and BIC() are not
defined for it.
The log-likelihood is computed for each target at each posterior sample.
For binomial and Poisson models, each observation consists of a pair of
counts (ai/ci or x1i/x2i) that together define a single effect size estimate.
Estimate-unit columns condition on the retained observations in each
declared dependency block. For Gaussian targets after integrating their
declared local Gaussian sources, including correlated known-V
brma.mv() and specialized multilevel normal models, these are
Schur conditional scores p(y_i \mid y_{-i}, \theta); their row sum
generally is not the full joint likelihood. Likelihood powers and
their normalizing constants are retained inside the local-effect integral
for weighted Gaussian cluster models. The observation CDF used by residuals
remains unpowered. Numerically unresolved retained moments raise
RoBMA_weighted_gaussian_unavailable.
Likelihood powers and
retained-sampling context follow the declared target. Independent
observations reduce to ordinary pointwise contributions. Cluster-unit
columns delete each complete cluster jointly.
Sampling-conditioned selection models retain the declared remaining sampling
errors and random context for estimate deletion, including ordinary component
branches and constant selection weights. Cluster deletion keeps its distinct
joint target. Earlier affected estimate scores must be recomputed.
Estimate-unit GLMM draws integrate the nuisance base rate or log-rate over
its prior: point priors and untruncated beta (base rate) and normal
(log-rate) priors adaptively, other priors on a refined prior-CDF grid; a
uniform(0, 1) base-rate prior is a Beta(1, 1) prior and is integrated
adaptively. The adaptive Gauss-Hermite rules raise the quadrature order until
successive orders agree within the tolerance; this agreement is an empirical
refinement check, not an error bound. The grid is accepted only when its log-likelihood changes by less
than 1e-6 between refinements. Any nuisance prior without an adaptive route
(other than an untruncated beta base rate or an untruncated normal log-rate;
truncated ones take the grid too) can fail to reach this, especially
with few events or very large arms, and then stops with the error class
RoBMA_glmm_grid_nonconvergence described below; gamma, lognormal, and
inverse-gamma log-rate priors and lognormal base-rate priors are examples. A
beta base-rate prior or a normal log-rate prior avoids it. The automatic
computation after fitting (the autocompute.loo and autocompute.waic
options) warns instead and returns the fit without LOO/WAIC.
Numerical quadrature failures share class RoBMA_glmm_numerical_error.
AGHQ failures have class RoBMA_glmm_aghq_nonconvergence; prior-CDF refinement
failures retain RoBMA_glmm_grid_nonconvergence. Their fields identify the
outcome family, observation, and available sample/refinement diagnostics.
A beta baserate prior whose shapes are too extreme for the prior-CDF grid to
be represented in double precision is unavailable and raises
RoBMA_glmm_prior_unavailable, also of class RoBMA_glmm_numerical_error.
Cluster-unit GLMM draws are unavailable until certified nested
adaptive quadrature is implemented.
Value
An S \times K or S \times G matrix of pointwise
log-likelihood draws with RoBMA_target metadata.
See Also
Log Marginal Likelihood for brma Objects
Description
Extract the log marginal likelihood from a brma model.
The marginal likelihood must first be computed using add_marglik.
Usage
## S3 method for class 'brma'
logml(x, ...)
Arguments
x |
a brma model object. |
... |
additional arguments (currently not used). |
Details
This function extracts the log marginal likelihood from the bridge sampling
object that was previously computed and stored using add_marglik.
Product-space model-averaging objects (BMA.norm, BMA.glmm,
BMA.mv, RoBMA, and RoBMA.mv) do not expose
bridge-sampling marginal likelihoods.
For repeated standardized results, this method returns the stored scalar
median of the included log marginal likelihoods. Legacy raw bridge lists
use the upstream scalar median method. Use bridge_sampler to
extract the raw bridge repetitions, or bf and
post_prob to compare models across repetitions.
Value
A scalar numeric value representing the log marginal likelihood.
See Also
add_marglik, bridge_sampler.brma,
bf.brma, post_prob.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_marglik(fit)
logml(fit)
}
## End(Not run)
LOO-PSIS for brma Objects
Description
Extract the LOO-PSIS object from a brma model object.
The LOO must first be computed using add_loo.
Usage
## S3 method for class 'brma'
loo(x, unit = "estimate", ...)
Arguments
x |
a brma model object. |
unit |
output/deletion unit. See |
... |
additional arguments (currently unused). |
Details
This function extracts the LOO object that was previously computed and
stored using object <- add_loo(object, unit = unit). If LOO has not
been computed for the requested unit, an error is thrown.
This is the RoBMA S3 generic and brma method. Use
loo directly for raw log-likelihood arrays or matrices.
Value
An object of class c("psis_loo", "loo") as returned by
loo.
See Also
add_loo, loo,
loo_compare, pareto_k_ids
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_loo(fit)
loo_fit <- loo(fit)
print(loo_fit)
}
## End(Not run)
Compare brma Models Using LOO
Description
Compare multiple brma models using LOO-PSIS cross-validation.
This is a convenience wrapper around loo_compare.
Usage
## S3 method for class 'brma'
loo_compare(x, ..., unit = "estimate")
Arguments
x |
a brma model object (the first model to compare). |
... |
additional brma model objects or |
unit |
output/deletion unit used when extracting LOO from brma objects. |
Details
This function compares models based on their expected out-of-sample predictive performance (ELPD).
Important for model comparison: When comparing models via
loo_compare, the selection is based on expected
predictive performance for the documented deletion target, not in-sample
fit. For dependent estimates, deleting one estimate may retain other
observations from its fitted dependency block; this is not new-group
prediction.
RoBMA rejects comparisons with different outcome targets/data, unit,
or retained context. A known sampling covariance without correlated blocks
(e.g., V = diag(sei^2) in brma.mv) is the outcome data
of its standard errors, whereas a correlated V is a different target.
The same compatibility key is applied
separately to LOO and WAIC; the two criteria cannot be mixed in one
comparison table. Sampled versus marginalized local-effect provenance does
not by itself block comparison.
Value
The comparison returned by loo_compare for the
stored results: a data frame of class "compare.loo" with one row per
model, ordered by expected predictive performance, which prints as loo
prints it. The models are named model1, model2, ... unless
the call names them.
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit_bias <- RoBMA(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit_nobias <- BMA(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit_bias <- add_loo(fit_bias)
fit_nobias <- add_loo(fit_nobias)
loo_compare(fit_bias, fit_nobias)
loo_compare(loo(fit_bias), loo(fit_nobias))
}
## End(Not run)
Compare loo Objects Using LOO
Description
Method for comparing RoBMA-targeted loo or waic
objects directly.
Usage
## S3 method for class 'loo'
loo_compare(x, ..., unit = "estimate")
Arguments
x |
a RoBMA-targeted |
... |
additional RoBMA-targeted |
unit |
output/deletion unit used when extracting LOO from brma objects. |
Value
The comparison returned by loo_compare for the
stored results: a data frame of class "compare.loo" with one row per
model, ordered by expected predictive performance, which prints as loo
prints it. The models are named model1, model2, ... unless
the call names them.
See Also
Predictive Model Weights for brma Objects
Description
Compute stacking or pseudo-BMA weights from LOO results already
stored in multiple brma objects.
Usage
## S3 method for class 'brma'
loo_model_weights(
x,
...,
unit = "estimate",
method = c("stacking", "pseudobma"),
optim_method = "BFGS",
optim_control = list(),
BB = TRUE,
BB_n = 1000,
alpha = 1,
r_eff_list = NULL,
cores = getOption("mc.cores", 1)
)
Arguments
x |
a |
... |
additional |
unit |
output/deletion unit used when extracting stored LOO results from
|
method |
weighting method; |
optim_method, optim_control |
optimization method and controls for
stacking. See |
BB, BB_n, alpha |
Bayesian-bootstrap controls for pseudo-BMA weighting.
See |
r_eff_list |
optional relative effective sample sizes. Retained for the
upstream interface and ignored when stored |
cores |
number of cores passed to |
Details
Each brma object must first be updated with
object <- add_loo(object, unit = unit). All models must use the same
outcome data, deletion unit, and likelihood target. RoBMA validates
these targets before delegating to loo::loo_model_weights().
Model names are derived from the supplied model expressions. See
loo_model_weights for details about stacking, pseudo-BMA,
and pseudo-BMA+.
Value
A named numeric vector containing one predictive weight per model.
See Also
add_loo, loo.brma,
loo_compare.brma, loo_model_weights
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit_bias <- RoBMA(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit_nobias <- BMA(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit_bias <- add_loo(fit_bias)
fit_nobias <- add_loo(fit_nobias)
loo_model_weights(fit_bias, fit_nobias)
}
## End(Not run)
Extract Normalized PSIS Weights from brma Object
Description
Extract the normalized Pareto smoothed importance sampling (PSIS) weights from a brma model object.
Usage
## S3 method for class 'brma'
loo_weights(object, unit = "estimate", ...)
Arguments
object |
a brma model object. |
unit |
output/deletion unit. See |
... |
currently unused. |
Details
LOO must first be computed with
object <- add_loo(object, unit = unit). This method extracts the
stored PSIS object and does not compute LOO. It does not compute weights
across models. For predictive model weights, use
loo_model_weights(model_1, model_2); for a model comparison table,
use loo_compare(model_1, model_2).
When the score integrates local random effects, these weights reweight global-parameter draws. They must not be applied to full-data sampled local effects as though those were draws from the deletion posterior; local-effect calculations require the corresponding retained-data reconstruction.
Value
An S x K matrix for estimate-unit LOO, or S x G
matrix for cluster-unit LOO, with posterior samples in rows and LOO targets
in columns. Columns are normalized to sum to one.
See Also
loo.brma, loo_compare.brma,
loo_model_weights.brma
Estimated Marginal Means
Description
S3 generic for estimated marginal means. The brma
method works with fitted moderator models and stores the BayesTools
marginal-inference object for summary() and plot().
Usage
marginal_means(object, ...)
Arguments
object |
a fitted model object. |
... |
additional arguments passed to methods. |
Value
A method-specific estimated marginal means object.
See Also
summary(), plot(), summary.brma(), regplot()
Estimated Marginal Means for brma Objects
Description
Computes estimated marginal means for a fitted brma
object with moderators using BayesTools::as_marginal_inference().
Alternative-conditioned marginal means condition on the union of every
nonzero formula coefficient contributing to the corresponding output cell.
A location intercept fixed at zero is omitted whenever moderators are
present.
Usage
## S3 method for class 'brma'
marginal_means(
object,
null_hypothesis = 0,
normal_approximation = FALSE,
n_samples = 10000,
output_measure = NULL,
transform = NULL,
bf = NULL,
parameter = NULL,
type = NULL,
levels = NULL,
density_method = c("KDE", "qCMDE", "IWMDE"),
density_control = NULL,
...
)
Arguments
object |
a fitted |
null_hypothesis |
point null hypothesis used for inclusion Bayes
factors, specified on the fitted linear-predictor scale. Defaults to
|
normal_approximation |
whether the prior and posterior density at the
null hypothesis should be approximated with a normal distribution (the
BayesTools normal approximation of the Savage-Dickey density ratio) instead
of a kernel density estimate. Defaults to |
n_samples |
number of samples/grid points used by BayesTools for
marginal prior densities. Defaults to |
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
bf |
whether inclusion Bayes factors should be shown by default in
summaries. Defaults to |
parameter, type, levels |
optional selectors restricting qCMDE/IWMDE
density precomputation to a marginal-means parameter, output type, or factor
levels. |
density_method |
posterior density method. |
density_control |
named list of density-estimation settings for
precomputed qCMDE/IWMDE methods. It is rejected with an error when
|
... |
unused additional arguments. Supplied arguments trigger a warning. |
Value
A list of class marginal_means.brma. Its stable fields are
inference, parameters, term_map, formula,
null_hypothesis, normal_approximation, n_samples, conditional_rule,
input_measure, effect_transform, model_averaged,
density_method, point_ordinate_supported, bf,
name, and source_object. qCMDE/IWMDE objects additionally
contain density_diagnostics, ordinate_diagnostics,
density_settings, and ordinate_settings.
See Also
summary(), plot(), summary.brma(), regplot()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(yi = yi, vi = vi, mods = ~ alloc, data = dat, measure = "RR")
mm <- marginal_means(fit)
summary(mm)
plot(mm, parameter = "alloc")
}
## End(Not run)
Number of Observations for brma Objects
Description
Extract the number of observations (studies/estimates) from a fitted brma object.
Usage
## S3 method for class 'brma'
nobs(object, ...)
Arguments
object |
a fitted brma object |
... |
additional arguments (currently ignored) |
Value
An integer giving the number of observations.
See Also
Plots brma Object
Description
plot.brma visualizes posterior
(and prior) distribution a brma object.
Usage
## S3 method for class 'brma'
plot(
x,
parameter,
parameter_mods,
parameter_scale,
prior = FALSE,
standardized_coefficients = FALSE,
conditional = FALSE,
output_measure = NULL,
transform = NULL,
plot_type = "base",
dots_prior = NULL,
density_method = c("KDE", "qCMDE", "IWMDE"),
density_control = NULL,
component = "auto",
...
)
## S3 method for class 'brma'
lines(
x,
parameter = NULL,
parameter_mods = NULL,
parameter_scale = NULL,
prior = FALSE,
standardized_coefficients = FALSE,
conditional = FALSE,
output_measure = NULL,
transform = NULL,
plot_type = "base",
dots_prior = NULL,
density_method = c("KDE", "qCMDE", "IWMDE"),
density_control = NULL,
component = "auto",
...
)
Arguments
x |
a fitted |
parameter |
a parameter to be plotted. Defaults to |
parameter_mods |
legacy moderator selector. Prefer |
parameter_scale |
legacy scale-regression selector. Prefer
|
prior |
whether prior distribution should be added to
figure. Defaults to |
standardized_coefficients |
whether to plot moderator and
scale-regression coefficients on the standardized predictor scale. Defaults
to |
conditional |
whether to plot the conditional posterior distribution
for RoBMA product-space objects. Defaults to |
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional plotting transformation. |
plot_type |
whether to use a base plot |
dots_prior |
list of additional graphical arguments
to be passed to the plotting function of the prior
distribution. Supported arguments are |
density_method |
posterior density method. |
density_control |
named list of density-estimation settings. Supported
entries are |
component |
parameter component. Defaults to |
... |
list of additional graphical arguments
to be passed to the plotting function. Supported arguments
are |
Details
A qCMDE/IWMDE request that the fitted model does not support stops
before any density is estimated with an error of class
RoBMA_density_method_unavailable and one class naming the cause:
RoBMA_density_method_random_unknown_v (brma.mv() random-formula models
without known V), RoBMA_density_method_scale_components
(component-specific scale formulas), or RoBMA_density_method_glmm (IWMDE
for binomial and Poisson GLMMs). Requests that are unavailable for the
plotted quantity stop with the same parent class and
RoBMA_density_method_conditional_random (conditional random-effect plots,
which are KDE-only), RoBMA_density_method_random_target (a random-effect
quantity without a supported scalar random-component coordinate),
RoBMA_density_method_bias_target (a composite weightfunction target; use
density_method = 'KDE'), or
RoBMA_density_method_original_scale (a coefficient or factor cell whose
original-scale value is not a linear combination of its fitted
coefficients, such as the exponentiated intercept of a scale formula with
standardized predictors; use standardized_coefficients = TRUE). A density
whose construction fails stops with an error of class
RoBMA_density_construction_error (a RoBMA_density_error); use
density_method = "KDE" to estimate
it from the posterior draws. A fitted chain with no eligible row of the
target adds the class RoBMA_density_chain_coverage, and the message names
longer chains and their convergence as the other remedy.
hypothesis() refuses qCMDE/IWMDE for the same causes with these classes
after its own. plot_prior() stops with RoBMA_density_method_original_scale
for the prior of a term with several fitted coordinates whose original-scale
coordinates the standardization changes (see there).
A returned qCMDE/IWMDE estimate that fails the density availability
checks raises a RoBMA_density_plot_error identifying the plotted parameter.
Its density_diagnostics field contains the returned diagnostic records,
including computed density values and selected rows, without executable
estimate plans that could retain the fitted object.
lines.brma() adds the posterior density to an existing base
plot. Omit add: this method always adds, and supplying add
triggers an error. With plot_type = "ggplot", it returns ggplot2 layer(s) that can
be added to a plot.brma(..., plot_type = "ggplot") object with
+. For base plots containing point masses, the initial
plot.brma() call establishes the secondary probability axis and
lines.brma() reuses it across fitted objects. An overlaid point mass
outside the initial ylim2 is clipped with a warning.
Value
plot.brma returns either NULL if plot_type = "base"
or a ggplot2 object (a named list of plots for a whole factor term)
if plot_type = "ggplot".
lines.brma returns NULL for plot_type = "base" and
ggplot2 layer(s) for plot_type = "ggplot".
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
plot(fit, parameter = "mu")
lines(fit, parameter = "mu", col = "blue", lwd = 2)
ggplot_fit <- plot(fit, parameter = "mu", plot_type = "ggplot")
ggplot_fit + lines(fit, parameter = "mu", plot_type = "ggplot", col = "blue")
plot(fit, parameter = "tau", prior = TRUE)
plot(fit, parameter = "PET")
}
## End(Not run)
Plot Estimated Marginal Means
Description
Plots estimated marginal means stored in a
marginal_means.brma object using BayesTools::plot_marginal().
Usage
## S3 method for class 'marginal_means.brma'
plot(
x,
parameter,
type = NULL,
prior = FALSE,
plot_type = "base",
dots_prior = NULL,
output_measure = NULL,
transform = NULL,
density_method = NULL,
density_control = NULL,
add = FALSE,
...
)
## S3 method for class 'marginal_means.brma'
lines(x, parameter, prior = FALSE, ...)
Arguments
x |
a |
parameter |
moderator term to plot. Use the original term name, for
example |
type |
for RoBMA product-space objects, whether to plot model-averaged
( |
prior |
whether the marginal prior distribution should be added to the
plot. Defaults to |
plot_type |
whether to use base R graphics ( |
dots_prior |
list of additional graphical arguments passed to the prior plotting function. |
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
density_method |
posterior density method. The default |
density_control |
named list of qCMDE/IWMDE density-estimation settings.
Supported entries are |
add |
whether to add the densities to an existing plot. This is used by
|
... |
additional graphical arguments passed to
|
Details
lines.marginal_means.brma() adds posterior densities to an
existing base plot. With plot_type = "ggplot", it returns ggplot2
layer(s) that can be added to a marginal-means plot with +.
Value
NULL invisibly if plot_type = "base" or a ggplot object
if plot_type = "ggplot".
Plot Zplot Results
Description
Plots a zplot visualization showing the histogram of observed z-statistics overlaid with model-implied densities.
Usage
## S3 method for class 'zplot_brma'
plot(
x,
plot_type = "base",
probs = c(0.025, 0.975),
max_samples = if (inherits(x, "brma.mv")) 1000 else 10000,
plot_fit = TRUE,
plot_extrapolation = FALSE,
plot_ci = TRUE,
plot_thresholds = TRUE,
from = -6,
to = 6,
by.hist = 0.5,
length.out.hist = NULL,
by.lines = 0.05,
length.out.lines = NULL,
dots_hist = NULL,
dots_fit = NULL,
dots_extrapolation = NULL,
dots_thresholds = NULL,
integration_control = x[["zplot"]][["data"]][["integration_control"]],
parallel = FALSE,
cores = min(4, RoBMA.get_option("max_cores")),
...
)
Arguments
x |
a zplot_brma object. |
plot_type |
graphics system: |
probs |
quantiles for credible intervals. Defaults to |
max_samples |
maximum posterior samples for density estimation.
Defaults to 1000 for |
plot_fit |
whether to show fitted density (with bias adjustments).
Defaults to |
plot_extrapolation |
whether to show extrapolated density (bias removed).
Defaults to |
plot_ci |
whether to show credible interval bands. Defaults to |
plot_thresholds |
whether to show significance threshold lines.
Defaults to |
from, to |
z-value range for plotting. Defaults to |
by.hist |
bin width for histogram. Defaults to 0.5. |
length.out.hist |
number of histogram bins (alternative to |
by.lines |
step size for density lines. Defaults to 0.05. |
length.out.lines |
number of density points (alternative to |
dots_hist |
graphical parameters for histogram (list). |
dots_fit |
graphical parameters for fit lines (list). |
dots_extrapolation |
graphical parameters for extrapolation lines (list). |
dots_thresholds |
graphical parameters for threshold lines (list). |
integration_control |
numerical integration settings created by
|
parallel |
whether to distribute multivariate selection-model density
calculations across local workers. Defaults to |
cores |
number of local workers when |
... |
additional graphical parameters passed to components, such as
|
Details
All model-implied curves use the conditioning_depth stored by
as_zplot(). Recreate the zplot object to change the predictive target.
The curves are posterior means of the density at each z value. Their credible
bands (plot_ci = TRUE) are pointwise Harrell-Davis quantiles of the
posterior density draws at the probabilities probs, computed by
BayesTools::harrell_davis_quantile(). They estimate the same quantiles as the
empirical quantiles of the draws but smooth the kinks that the empirical
quantiles show along z. The bands remain pointwise, and, because every draw
contributes, they can differ visibly from the empirical quantiles when few
draws are used (max_samples below a few hundred). Near the edge of a
point mass in the draws (e.g., draws of models that fix the plotted quantity
in a model-averaged posterior) the band blends the point mass and the
remaining draws, and extreme probabilities (e.g., probs = c(.0005, .9995))
are not estimated more accurately than by the empirical quantiles; see
BayesTools::harrell_davis_quantile() for these caveats.
The plot can display two density curves:
- Fit (black)
Model-implied density including publication bias adjustments. This represents the expected distribution of z-statistics given the estimated selection process. Shown by default.
- Extrapolation (blue)
The bias-adjusted reference without selective reporting. Multivariate models, retained estimate-level or sampling-error sources, applicable integrated contexts, and best-rule selection models use the normalized pre-selection Gaussian marginal. Released univariate product targets retain their inverse-weight scaling convention. Shown only when
plot_extrapolation = TRUE, since the extrapolated curve rescales the display by an inferred selection convention rather than describing the observed literature.
Value
NULL invisibly for base graphics, or a ggplot2 object.
See Also
hist.zplot_brma(), lines.zplot_brma(), summary.zplot_brma()
Plot MCMC Diagnostics
Description
plot_diagnostic creates visual MCMC diagnostics for a
fitted brma object. Convenience wrappers are available for trace, density,
and autocorrelation plots.
Usage
plot_diagnostic(x, ...)
## S3 method for class 'brma'
plot_diagnostic(
x,
parameter = NULL,
parameter_mods = NULL,
parameter_scale = NULL,
type,
plot_type = "base",
lags = 30,
component = "auto",
...
)
plot_diagnostic_autocorrelation(x, ...)
## S3 method for class 'brma'
plot_diagnostic_autocorrelation(
x,
parameter = NULL,
parameter_mods = NULL,
parameter_scale = NULL,
type = "autocorrelation",
plot_type = "base",
lags = 30,
component = "auto",
...
)
plot_diagnostic_trace(x, ...)
## S3 method for class 'brma'
plot_diagnostic_trace(
x,
parameter = NULL,
parameter_mods = NULL,
parameter_scale = NULL,
type = "trace",
plot_type = "base",
lags = 30,
component = "auto",
...
)
plot_diagnostic_density(x, ...)
## S3 method for class 'brma'
plot_diagnostic_density(
x,
parameter = NULL,
parameter_mods = NULL,
parameter_scale = NULL,
type = "density",
plot_type = "base",
lags = 30,
component = "auto",
...
)
Arguments
x |
a fitted brma object |
... |
additional graphical arguments passed through RoBMA's diagnostic
setup to |
parameter |
base parameter to plot. Defaults to |
parameter_mods |
legacy moderator selector. Prefer |
parameter_scale |
legacy scale-regression selector. Prefer
|
type |
diagnostic plot type. Convenience wrappers set a type-specific
default but still forward this argument to |
plot_type |
whether to use a base plot |
lags |
number of lags for autocorrelation plots. Defaults to 30. |
component |
parameter component. Defaults to |
Value
plot_diagnostic returns the object returned by
BayesTools::JAGS_diagnostics(), including a list when several
coordinate plots are produced, invisibly for base graphics.
See Also
Plot PET-PEESE Fit of brma Object
Description
plot_pet_peese visualizes posterior
(and prior) PET-PEESE fit of a brma object.
Usage
plot_pet_peese(x, ...)
## S3 method for class 'brma'
plot_pet_peese(
x,
show_data = TRUE,
prior = FALSE,
plot_type = "base",
dots_prior = NULL,
...
)
Arguments
x |
a fitted brma object with a PET or PEESE component. |
... |
list of additional graphical arguments
to be passed to the plotting function. Supported arguments
are |
show_data |
whether the observed effect sizes should be added to
figure. Defaults to |
prior |
whether prior distribution should be added to
figure. Defaults to |
plot_type |
whether to use a base plot |
dots_prior |
list of additional graphical arguments
to be passed to the plotting function of the prior
distribution. Supported arguments are |
Details
The plot shows observed yi values against sei. PET
regression uses \mu + PET \cdot se_i; PEESE regression uses
\mu + PEESE \cdot se_i^2, with the fitted effect direction. Models
with moderators are not supported because the fitted curve depends on the
moderator values at which it is evaluated.
Value
plot_pet_peese returns either NULL invisibly if
plot_type = "base" or a ggplot2 object if
plot_type = "ggplot".
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
plot_pet_peese(fit)
}
## End(Not run)
Plot Prior Distributions
Description
plot_prior visualizes prior distributions stored in
brma, BMA, and RoBMA objects.
This is especially useful for objects created with only_priors = TRUE.
Usage
plot_prior(x, ...)
## S3 method for class 'prior'
plot_prior(x, plot_type = "base", ...)
## S3 method for class 'brma'
plot_prior(
x,
parameter = "mu",
parameter_mods,
parameter_scale,
standardized_coefficients = TRUE,
output_measure = NULL,
transform = NULL,
plot_type = "base",
component = "auto",
...
)
Arguments
x |
a |
... |
additional arguments passed to the prior plotting method. For
mixed continuous and point priors, |
plot_type |
whether to use a base plot |
parameter |
character. Base parameter to plot. Defaults to |
parameter_mods |
legacy moderator selector. Prefer |
parameter_scale |
legacy scale-regression selector. Prefer
|
standardized_coefficients |
whether to plot moderator and scale-regression
priors on the standardized predictor scale. Defaults to |
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
component |
parameter component. Defaults to |
Details
output_measure and transform transform the prior
plotting scale only for effect-size location priors ("mu" or the
meta-regression intercept). For base plots, the probability mapping created
by plot_prior() is reused by subsequent posterior
lines.brma() calls, including overlays from other fitted objects.
PET and PEESE priors, single or mixed, show bias-only
effect-versus-standard-error curves by default, with a zero location
contribution, the effect direction of the object (override it with
effect_direction), and the declared model weights.
Use individual = TRUE for coefficient densities, or supply
prior_list_mu to request full regression curves with explicit location
priors, as supported by BayesTools::plot_prior_list().
The random-effect quantities of fitted brma.mv, BMA.mv, and
RoBMA.mv objects are selected by their names in parameter,
such as "tau", "tau_total", "tau2",
"tau2_prop(study)", or "study: tau" ("tau" stops as
ambiguous when several blocks have an SD). A quantity that is one declared
prior (the SD of a block, the total SD of a variance allocation, or a
correlation with its own prior) shows that prior. Any other quantity
(a variance, a share of the total variance, the SD of a component of an
allocation, and the quantities of gated allocations) shows the prior law it
follows from the declared priors, the density that plot() overlays
with prior = TRUE, drawn without a posterior; point masses (for
example of inclusion gates) are drawn as arrows. For these laws,
xlim, n_points, par_name, and graphical arguments
apply as for other priors, while x_seq and x_range_quant
stop. A quantity without a prior density stops with the classes
BayesTools_hypothesis_target and BayesTools_hypothesis_unavailable.
standardized_coefficients selects the fitted (default) or the
original predictor scale of these laws. Objects created with
only_priors = TRUE have no fitted random-effect quantities; print
their random-effect priors with
print_prior(x, parameter = "random").
Inconsistent random-allocation parent metadata stop with
RoBMA_random_prior_derivation_error; cycles additionally carry
RoBMA_random_allocation_cycle, and unknown parents carry
RoBMA_random_allocation_parent_unavailable. A parent chain beyond the
supported depth of 16 allocations carries
RoBMA_random_allocation_depth_unavailable. The condition retains
its reason and visited allocation_chain. Other source errors
propagate with their original classes and causes.
A term with several fitted coordinates (a factor with three or more levels
or with independent contrasts, and the interactions of such a factor) has
an original-scale prior only when the standardization of continuous
predictors leaves its coordinates unchanged. With
standardized_coefficients = FALSE, the prior of such a term whose
coordinates the standardization changes (a factor or factor-by-factor
interaction next to its interaction with a standardized predictor, and that
interaction term) stops with an error of class
RoBMA_density_method_original_scale and its parent
RoBMA_density_method_unavailable; use
standardized_coefficients = TRUE. The other terms (including factors
and factor-by-factor interactions without an interaction with a
standardized predictor) are plotted as before.
Value
plot_prior returns the selected prior plotting method's
result, invisibly for base plots (which may include plot-data metadata), or
a ggplot2 object for plot_type = "ggplot". If multiple
parameters are requested, a named list is returned, invisibly for base plots.
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
priors <- BMA(
yi = yi,
vi = vi,
mods = ~ Preregistered,
data = dat.lehmann2018,
measure = "SMD",
only_priors = TRUE
)
plot_prior(priors, parameter = "mu")
plot_prior(priors, parameter = "tau")
plot_prior(priors, parameter = "Preregistered", component = "mods")
}
## End(Not run)
Plots Weight Function of brma Object
Description
plot_weightfunction.brma visualizes the posterior
(and optionally prior) publication-bias weight function of a brma object.
Usage
plot_weightfunction(x, ...)
## S3 method for class 'brma'
plot_weightfunction(
x,
rescale_p_values = TRUE,
prior = FALSE,
plot_type = "base",
show_data = TRUE,
dots_data = NULL,
dots_prior = NULL,
...
)
Arguments
x |
a fitted |
... |
list of additional graphical arguments
to be passed to the plotting function. Supported arguments
are |
rescale_p_values |
whether to rescale p-values to the interval shown
by the weightfunction plot. Defaults to |
prior |
whether prior distribution should be added to
figure. Defaults to |
plot_type |
whether to use a base plot |
show_data |
whether observed p-values should be shown as rug marks on
the weightfunction axis, using its one-sided or two-sided convention.
Defaults to |
dots_data |
list of additional graphical arguments for observed
p-value rug marks. Supported arguments include |
dots_prior |
list of additional graphical arguments
to be passed to the plotting function of the prior
distribution. Supported arguments are |
Value
plot_weightfunction.brma returns either NULL if
plot_type = "base" or a ggplot2 object if
plot_type = "ggplot".
The method errors for fitted objects without a weightfunction component.
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bselmodel(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
plot_weightfunction(fit)
plot_weightfunction(fit, prior = TRUE)
}
## End(Not run)
Pooled Effect Size
Description
Computes the pooled (aggregated) effect size estimate from a fitted model.
Usage
pooled_effect(object, ...)
Arguments
object |
a fitted model object |
... |
additional arguments passed to methods |
Value
Method-specific return value, typically a summary table or posterior samples of the pooled effect size.
See Also
Pooled Effect Size for brma Objects
Description
Computes the pooled effect and prediction interval at the average expanded moderator design of a fitted brma object.
Usage
## S3 method for class 'brma'
pooled_effect(
object,
bias_adjusted = TRUE,
output_measure = NULL,
transform = NULL,
probs = c(0.025, 0.975),
conditional = FALSE,
...
)
Arguments
object |
a fitted brma object |
bias_adjusted |
whether to adjust for publication bias. Defaults to
|
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
probs |
quantiles of the posterior distribution to be displayed.
Defaults to |
conditional |
whether to return the pooled effect conditional on the
effect component for RoBMA product-space objects. Defaults to |
... |
additional arguments passed to |
Details
This function is a convenience wrapper around predict.brma(...,
type = "terms", newdata = TRUE, bias_adjusted = TRUE, quiet = TRUE) that
adds the prediction interval columns.
The fixed-location model is evaluated at the average expanded moderator design. Because the location predictor is linear in its design, this equals averaging its fitted-design posterior draws directly.
For meta-regression models, the pooled effect averages the effect size estimate across moderator levels proportionately to the levels observed in the data. This provides an estimate representative of the sample of studies.
For brma.mv() models and models with factor-specific or random-slope
terms, the average expanded design can be synthetic and need not correspond
to a single realizable outcome or study. The pooled effect and its prediction
interval then describe that linear composite and should be interpreted only
when the composite has a meaningful scientific interpretation. Use
predict(..., newdata = ...) for a specified realizable design.
For models without moderators, this returns the single mu parameter. The
prediction interval is marginal over one new true effect at the same average
location and random-effect design, with the scale given by the mean of the
observation-specific tau, as in pooled_heterogeneity(). It therefore
uses pooled_heterogeneity(component = "total"), rather than the
observed-design RMS heterogeneity reported by
summary_heterogeneity(). For known-R random
effects this is a unit-kernel reference interval; use predict() for
an interval tied to a fitted group and its known covariance multiplier.
Value
A brma_samples object containing posterior samples. When printed,
displays a one-row summary table whose PI columns contain posterior
prediction quantiles. They are computed exactly from the posterior draws of
the pooled location and heterogeneity, as quantiles of the normal mixture
over the draws, so they involve no random numbers. Use summary(), or
as.data.frame(summary(x)), to obtain the table; as.data.frame(x)
returns the posterior draws.
The samples can be converted to posterior draws formats using as_draws().
See Also
predict.brma(), pooled_heterogeneity(), blup()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
pooled_effect(fit)
}
## End(Not run)
Pooled Heterogeneity
Description
Computes method-specific pooled (aggregated) heterogeneity from a fitted model.
Usage
pooled_heterogeneity(object, ...)
Arguments
object |
a fitted model object |
... |
additional arguments passed to methods |
Value
Method-specific return value, typically a summary table or posterior samples of the pooled heterogeneity.
See Also
Pooled Heterogeneity for brma Objects
Description
Computes heterogeneity (tau) of a fitted brma object at the average fitted scale design (the mean of the observation-specific tau) and, for random-formula models, at the average expanded random-effect design.
Usage
## S3 method for class 'brma'
pooled_heterogeneity(
object,
probs = c(0.025, 0.975),
conditional = FALSE,
component = "all",
...
)
Arguments
object |
a fitted brma object |
probs |
quantiles of the posterior distribution to be displayed.
Defaults to |
conditional |
whether to return the pooled heterogeneity conditional on
the heterogeneity component for RoBMA product-space objects. Defaults to
|
component |
heterogeneity component to return for |
... |
additional arguments passed to |
Details
For location-scale models, the function returns the arithmetic mean over the
fitted rows of the observation-specific tau, as in 4.0.0; it equals
rowMeans(predict(object, type = "terms.scale")). It is not the root
mean square heterogeneity across the observed rows. Use
summary_heterogeneity() for the latter.
For models without scale regression, this returns the single tau parameter.
For multilevel (3-level) models, the returned tau is the total heterogeneity:
tau = sqrt(tau_within^2 + tau_between^2).
For brma.mv() models, one ordinary selected component is named
tau; a genuine variance-additive total is named tau_total; and a
mean-variance allocation anchor is named tau_common. These quantities
are available when a random formula is declared. For random-formula models,
component = "all"
returns one brma_samples object when there is a single heterogeneity
component and a named list when there are multiple components.
component = "total" computes the variance-additive total at the
average random-effect design. Random slopes are evaluated as
\bar q^T G \bar q, including within-block correlations. Default and
named allocation components retain their declared scale anchors; explicit
totals and pooled-effect prediction intervals use the full covariance of
the average design, including allocation-owned blocks.
With a known group covariance R, the
reported sd is the fitted multiplier of that kernel. It need not equal
every row's marginal standard deviation when \mathrm{diag}(R) is not
one. Row-specific marginal standard deviations are available from
predict(type = "terms.scale"). A scale formula of a random-formula model
enters the average random-effect design as the arithmetic mean of the
observation-specific tau, as for the univariate models.
predict(object, newdata = TRUE, type = "terms.scale") returns the same
component result: a named list for several components and one
brma_samples object for a single component.
For brma.mv() models and models with factor-specific or random-slope
terms, the average expanded random-effect design can be synthetic and need
not correspond to a single realizable outcome or study. The result is the
heterogeneity of that linear composite, not typical heterogeneity across the
observed designs. Interpret it only when the composite has a meaningful
scientific interpretation; use summary_heterogeneity() for
observed-design heterogeneity or predict(..., newdata = ...) for a
specified realizable design.
Value
A brma_samples object containing posterior samples. When printed,
displays a summary table. For decomposed brma.mv() models, a named
list of brma_samples objects is returned. Use summary() on an
individual object (as.data.frame() of an individual object returns its
draws) or as.data.frame() on the complete result to obtain
a summary data frame with component and parameter identifiers. Use
as.data.frame(format = "list") to retain separate component tables.
The samples can be converted to posterior draws formats using
as_draws().
See Also
predict.brma(), pooled_effect(), blup()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
pooled_heterogeneity(fit)
}
## End(Not run)
Posterior Model Probabilities for brma Objects
Description
Compute posterior model probabilities from marginal likelihoods of brma models.
Usage
## S3 method for class 'brma'
post_prob(x, ..., prior_prob = NULL, model_names = NULL)
Arguments
x |
a brma model object. |
... |
additional brma model objects. |
prior_prob |
numeric vector with prior model probabilities or weights. Values must be finite, nonnegative, have the same length as the retained models, and have a positive total. If omitted, a uniform prior is used. Finite comparisons combine the original weights with marginal likelihoods in log space and normalize the resulting probabilities. An exactly zero prior weight excludes that model. |
model_names |
character vector with model names. If |
Details
The marginal likelihoods must first be computed using add_marglik.
x and at least one additional brma model must be supplied.
Non-brma objects in ... are ignored with a warning. All retained
models must be fitted to the same outcome target/data, including outcome type
and, when present, likelihood weights. Cluster identifiers define model
structure and are not part of the outcome-data identity. A known sampling
covariance without correlated blocks (e.g., V = diag(sei^2) in
brma.mv) is the outcome data of its standard errors, whereas a
correlated V is a different target.
If any model contains repeated bridge estimates, comparisons retain those
repetitions regardless of model order. Models with fewer repetitions are
recycled to the largest repetition count with a warning, following
bridgesampling.
Standardized marginal-likelihood results must be finite. Legacy raw
"bridge_list" results retain non-finite repetitions and use upstream
comparison behavior through bridgesampling, with normalized prior
probabilities and its missing-value propagation, warnings, and errors.
Value
A named numeric vector with posterior model probabilities for single estimates, or a repetition-by-model numeric matrix when any model has repeated estimates. Each successfully evaluated comparison sums to one.
See Also
add_marglik, bridge_sampler.brma,
bf.brma, logml.brma
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit1 <- brma(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit2 <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
prior_effect = FALSE
)
fit1 <- add_marglik(fit1)
fit2 <- add_marglik(fit2)
post_prob(fit1, fit2)
}
## End(Not run)
Predict From brma Object
Description
predict.brma predicts values
Usage
## S3 method for class 'brma'
predict(
object,
newdata = NULL,
type = "terms",
as_measure = TRUE,
output_measure = NULL,
transform = NULL,
probs = c(0.025, 0.975),
bias_adjusted = FALSE,
quiet = FALSE,
conditional = FALSE,
V_new = NULL,
conditioning_depth = "marginal",
...
)
Arguments
object |
a fitted brma object |
newdata |
prediction data. Defaults to |
type |
type of prediction to be performed. Options are:
The released |
as_measure |
logical; whether to convert GLMM response predictions from
simulated counts to continuity-corrected effect-size estimators (logOR for
binomial, logIRR for Poisson). Defaults to |
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
probs |
quantiles of the posterior samples to be displayed when the
returned |
bias_adjusted |
whether predictions should adjust for publication bias.
Defaults to
When
For new outcomes, selection predictions draw retained contexts from their original Gaussian law, then sample each full publication event conditional on that context. Selected latent predictions additionally reconstruct the integrated true effects conditional on the selected response. At estimate depth, response prediction is a new replication event conditional on the fitted latent true effects; LOO-PIT instead uses deletion within the original publication event. Retained estimate-level effects use their fitted posterior values at estimate depth and fresh Gaussian draws for a new estimate within a fitted cluster. The fitted selection specification and prediction conditioning depth are separate choices. |
quiet |
logical; whether to suppress the informational message when conditional posterior samples are flattened to one chain. |
conditional |
whether to return conditional posterior predictions for
RoBMA product-space objects. For location predictions, samples are conditioned
on the effect component; for |
V_new |
optional sampling covariance for explicit
|
conditioning_depth |
random-effect conditioning depth for
|
... |
unused additional arguments. Supplied arguments trigger a warning. |
Details
Prediction has two independent axes. type selects the quantity:
fixed location ("terms"), latent true effect ("estimate"), or
observed outcome ("response"). conditioning_depth selects how
much of the fitted random-effect hierarchy is retained. In the specialized
multilevel model fitted with cluster,
y_{ij} = X_{ij}\beta + u_j + v_{ij} + \epsilon_{ij}, the targets are:
-
"marginal": condition on neitheru_jnorv_{ij}; -
"cluster": condition on fittedu_j, but draw a newv_{ij}; -
"estimate": draw the fitted latent effect from its posterior.
type = "response" adds \epsilon to the selected latent-effect
target. For normal fitted effects this includes the conditional latent
uncertainty, not only the BLUP mean. blup() and fitted(...,
conditioning_depth = "estimate") remain the conditional-mean interfaces.
For admitted weighted Gaussian selection models, reconstruction of fitted
integrated true effects uses the normalized conditional kernel
N(u;0,\tau^2)N(y;c+u,s^2)^w. Its conditioning variance is
s^2/w; the fitted global posterior and retained latent contributions
remain the supplied posterior. This post-fit augmentation does not assert
that likelihood powering commutes with integrating a latent effect.
Estimate-depth estimate and response targets record this policy and the
row-aligned likelihood weights in RoBMA_target$latent_augmentation.
Response replication adds the original sampling variance s^2.
Ordinary independent Gaussian selection predictions use exact diagonal-cell
chunk pricing after conservative fixed-geometry and output reserves. Other
model structures retain the dense covariance charge under the same budget.
The RoBMA.known_v_covariance_max_bytes option controls covariance
chunk memory. Selected predictions are reproducible for a fixed seed and
chunk budget, but changing this option can change the returned seeded draw
sequence because chunking changes the order of random-number consumption.
newdata supplies design values and grouping identities; it does not
select an estimand. Consequently, marginal prediction has the same law for
newdata = NULL and an equivalent explicit design. Matching fitted
grouping labels retains the requested dependence among new marginal draws
but does not reuse fitted random effects. Cluster- and estimate-depth
predictions require fitted identities and therefore currently reject
explicit newdata.
For binomial and Poisson GLMM response predictions, estimate depth uses the
fitted posterior nuisance base rate \pi_i or rate \phi_i.
Marginal and cluster depths describe a new estimate and therefore draw a new
nuisance rate independently from its model prior. Those predictions contain
a prior-predictive nuisance-rate component, which can dominate their width
when the nuisance prior is diffuse; fitted \pi_i/\phi_i values are
never silently reused for a marginal or cluster target.
For RoBMA product-space objects, conditional posterior predictions subset
posterior rows according to model indicators. This removes the original
chain structure, so returned brma_samples objects are intentionally
stored as one flattened chain.
Note that in contrast to predict, the type = "response" produces
predictions for the new effect size estimates. To obtain results corresponding to
metafor's predict function, use type = "terms" for the mean effect size
and type = "estimate" for true effects (prediction interval).
Likelihood weights: If the model was fitted with weights,
the weights affect the posterior fit, log-likelihood, LOO/WAIC, and
existing-data conditional diagnostics such as BLUP shrinkage and leverage.
They do not change the observation-level sampling error used by
type = "response" for normal models: response predictions simulate
raw future effect-size estimates with the supplied sei, not
sei / sqrt(weight).
For known-V brma.mv() models, explicit newdata
response and unadjusted selected latent prediction require V_new.
Random-formula models preserve
the joint random-effect structure selected by conditioning_depth and
then add V or V_new sampling noise. Cross-covariance with
observed rows is not supported. Explicit
newdata estimate/response predictions are not
available for brma.mv() objects with marginalized known-R
blocks, because their row multipliers are fitted-row metadata.
brma.mv() prediction results carry a
brma_mv_prediction_target attribute recording the formula,
random-effect, and response-generation target used.
For known-V models, the conditional random-effect predictions require
applying the inverse of the marginal covariance. A covariance that is too
ill-conditioned for that (a reciprocal condition number of about 2e-10
or less in any posterior draw used) is unavailable: the call stops with an
error of class RoBMA_known_v_precision_unavailable, whose parent class
is RoBMA_numerical_unavailable, instead of returning a rounded number.
The condition carries the draw positions (rows) and their
reciprocal_condition.
Value
A brma_samples object containing posterior samples. For
brma.mv() random-formula type = "terms.scale" predictions,
returns a named list of component-specific brma_samples objects; with
newdata = TRUE this component result is the component = "all"
result of pooled_heterogeneity (a named list for several
components, one brma_samples object for a single component), computed
with the arithmetic mean of the observation-specific tau of a scale formula;
its components are titled “Pooled Heterogeneity (<block>)” and
“Total Pooled Heterogeneity”.
When printed, each brma_samples object displays a summary table via
BayesTools::ensemble_estimates_table. The underlying samples matrix
can be accessed directly because the object inherits from matrix. For a
single brma_samples object, use summary(), or
as.data.frame(summary(x)), to obtain the summary table with component
and parameter identifiers; as.data.frame(x) returns the posterior
draws. A list of results (a brma_samples_list) coerces directly:
as.data.frame() of the list gives the summary table, and
as.data.frame(format = "list") retains separate tables. The samples
can also be converted to posterior draws formats
using as_draws() and related functions.
See Also
pooled_effect(), pooled_heterogeneity(), blup()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(
yi = yi,
vi = vi,
mods = ~ ablat + year,
data = dat,
measure = "RR",
seed = 1,
silent = TRUE
)
predict(fit, type = "terms")
predict(fit, newdata = TRUE, type = "terms")
predict(fit, newdata = data.frame(ablat = 50, year = 1970),
type = "estimate")
predict(fit, type = "estimate")
}
## End(Not run)
Print method for RoBMA_data objects
Description
Prints a concise summary of an RoBMA_data object.
Usage
## S3 method for class 'RoBMA_data'
print(x, n = 6, ...)
Arguments
x |
an RoBMA_data object |
n |
maximum number of rows to display for each component. Defaults to 6. |
... |
additional arguments (ignored) |
Value
Invisibly returns the input object.
Print brma_samples Object
Description
Prints a summary table of posterior samples using
BayesTools::ensemble_estimates_table. Returns the samples
invisibly for method chaining.
Usage
## S3 method for class 'brma_samples'
print(x, probs = NULL, ...)
Arguments
x |
a |
probs |
quantiles for credible intervals. If |
... |
additional arguments passed to
|
Value
Returns x invisibly.
Print Estimated Marginal Means
Description
Prints the estimated marginal means summary.
Usage
## S3 method for class 'marginal_means.brma'
print(x, ...)
Arguments
x |
a |
... |
additional arguments passed to |
Value
Returns x invisibly.
Print summary.brma_samples Object
Description
Prints a summary table of posterior samples using
BayesTools::ensemble_estimates_table. Returns the summary table
invisibly.
Usage
## S3 method for class 'summary.brma_samples'
print(x, probs = NULL, ...)
Arguments
x |
a |
probs |
quantiles for credible intervals. If |
... |
additional arguments passed to
|
Value
Returns the summary table invisibly.
Print Summary of Estimated Marginal Means
Description
Prints a summary table of estimated marginal means.
Usage
## S3 method for class 'summary.marginal_means.brma'
print(x, ...)
Arguments
x |
a |
... |
unused additional arguments. Supplied arguments trigger a warning. |
Value
Returns x invisibly.
Print Zplot Summary
Description
Print Zplot Summary
Usage
## S3 method for class 'summary.zplot_brma'
print(x, ...)
Arguments
x |
a summary.zplot_brma object. |
... |
additional arguments (currently unused). |
Value
Invisibly returns the summary object.
Print Summary of Heterogeneity
Description
Prints the heterogeneity summary table.
Usage
## S3 method for class 'summary_heterogeneity.brma'
print(x, ...)
Arguments
x |
a |
... |
additional arguments (currently ignored) |
Value
Returns x invisibly.
Print VIF Results
Description
Prints variance inflation factors and optional posterior correlation matrix.
Usage
## S3 method for class 'vif.brma'
print(x, digits = 3, ...)
Arguments
x |
a |
digits |
number of decimal places. Defaults to 3. |
... |
additional arguments (currently ignored) |
Value
Returns x invisibly.
Print Prior Distributions
Description
print_prior prints prior distributions stored in
brma, BMA, and RoBMA objects.
This is a user-facing helper for inspecting priors without extracting them
from the internal $priors list.
Usage
print_prior(x, ...)
## S3 method for class 'prior'
print_prior(x, ...)
## S3 method for class 'brma'
print_prior(
x,
parameter,
parameter_mods,
parameter_scale,
component = "auto",
...
)
Arguments
x |
a |
... |
additional arguments passed to the prior printing method. Use
|
parameter |
character. Base parameter to print. If omitted, all stored
prior distributions are printed.
Common options are |
parameter_mods |
legacy moderator selector. Prefer |
parameter_scale |
legacy scale-regression selector. Prefer
|
component |
parameter component. Defaults to |
Value
print_prior invisibly returns the selected prior distribution
(for a random-effect quantity that is not one declared prior, its prior
density, a BayesTools prior_linear_density).
If multiple parameters are requested, a named list of prior distributions is
returned invisibly.
See Also
plot_prior() BMA() RoBMA() brma() prior()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
priors <- BMA(
yi = yi,
vi = vi,
mods = ~ Preregistered,
data = dat.lehmann2018,
measure = "SMD",
only_priors = TRUE
)
print_prior(priors)
print_prior(priors, parameter = "mu")
print_prior(priors, parameter = "tau")
print_prior(priors, parameter = "Preregistered", component = "mods")
}
## End(Not run)
Prior Distribution
Description
Create prior distribution objects used by RoBMA and brma fitting functions.
Usage
prior(
distribution,
parameters,
truncation = list(lower = -Inf, upper = Inf),
prior_weights = 1
)
Arguments
distribution |
character. Prior distribution name. |
parameters |
list. Distribution parameters. |
truncation |
list with |
prior_weights |
numeric prior model weight. |
Details
This is RoBMA's re-export of BayesTools::prior(); supported
distribution names and parameter lists follow BayesTools.
Value
An object inheriting from prior.
Examples
prior("normal", list(mean = 0, sd = 0.5))
prior(
"normal",
list(mean = 0, sd = 0.5),
truncation = list(lower = 0, upper = Inf)
)
PEESE Prior
Description
Create PEESE publication-bias regression priors.
Usage
prior_PEESE(
distribution,
parameters,
truncation = list(lower = 0, upper = Inf),
prior_weights = 1
)
Arguments
distribution |
character. Prior distribution name. |
parameters |
list. Distribution parameters. |
truncation |
list with |
prior_weights |
numeric prior model weight. |
Details
This forwards to BayesTools::prior_PEESE() and uses the same
distribution and parameter conventions as prior().
Value
An object inheriting from prior with the prior.PEESE
marker class.
See Also
publication_bias_prior_specification
PET Prior
Description
Create PET publication-bias regression priors.
Usage
prior_PET(
distribution,
parameters,
truncation = list(lower = 0, upper = Inf),
prior_weights = 1
)
Arguments
distribution |
character. Prior distribution name. |
parameters |
list. Distribution parameters. |
truncation |
list with |
prior_weights |
numeric prior model weight. |
Details
This forwards to BayesTools::prior_PET() and uses the same
distribution and parameter conventions as prior(). By default, PET
priors are truncated to the positive half-line.
Value
An object inheriting from prior with the prior.PET
marker class.
See Also
publication_bias_prior_specification
Factor Prior
Description
Create priors on factor contrasts.
Usage
prior_factor(
distribution,
parameters,
truncation = list(lower = -Inf, upper = Inf),
prior_weights = 1,
contrast = "meandif"
)
Arguments
distribution |
character. Prior distribution name. |
parameters |
list. Distribution parameters. |
truncation |
list with |
prior_weights |
numeric prior model weight. |
contrast |
character. Contrast coding used for factor levels. Common
RoBMA model options are |
Details
Mean-difference and orthonormal contrasts require vector or multivariate priors. Treatment/dummy and independent contrasts use univariate simple priors per contrast coefficient.
Value
An object inheriting from prior, prior.factor, and a
contrast-specific marker class.
Informed Prior
Description
Create empirical informed prior distributions.
Usage
prior_informed(name, parameter = NULL, type = "smd")
Arguments
name |
character. Informed prior name. Supported examples include
|
parameter |
character. Parameter subset. Required for medicine priors and not needed for psychology priors. |
type |
character. Effect-size type. Medicine priors use values such as
|
Details
Further details can be found in van Erp et al. (2017), Gronau et al. (2017), Bartoš et al. (2021), and Bartoš et al. (2023).
Value
An object of class prior.
References
Bartoš F, Gronau QF, Timmers B, Otte WM, Ly A, Wagenmakers E (2021).
“Bayesian model-averaged meta-analysis in medicine.”
Statistics in Medicine, 40(30), 6743–6761.
doi:10.1002/sim.9170.
Bartoš F, Otte WM, Gronau QF, Timmers B, Ly A, Wagenmakers E (2023).
“Empirical prior distributions for Bayesian meta-analyses of binary and time-to-event outcomes.”
doi:10.48550/arXiv.2306.11468.
Preprint available at https://doi.org/10.48550/arXiv.2306.11468.
Gronau QF, Van Erp S, Heck DW, Cesario J, Jonas KJ, Wagenmakers E (2017).
“A Bayesian model-averaged meta-analysis of the power pose effect with informed and default priors: The case of felt power.”
Comprehensive Results in Social Psychology, 2(1), 123–138.
doi:10.1080/23743603.2017.1326760.
van Erp S, Verhagen J, Grasman RP, Wagenmakers E (2017).
“Estimates of between-study heterogeneity for 705 meta-analyses reported in Psychological Bulletin from 1990–2013.”
Journal of Open Psychology Data, 5(1), 1–5.
doi:10.5334/jopd.33.
Empty Prior
Description
Create an empty prior used to omit a model component.
Usage
prior_none(prior_weights = 1)
Arguments
prior_weights |
numeric prior model weight. |
Value
An object inheriting from prior and prior.none.
Ordered Factor Prior
Description
Create priors on ordered factor effects by separating a scalar total effect from its allocation across ordered-level increments.
Usage
prior_ordered(
total,
allocation = NULL,
contrast = "cumulative",
id = NULL,
prior_weights = 1
)
Arguments
total |
scalar prior for the sum of ordered increments. With
|
allocation |
allocation prior or fixed split. |
contrast |
ordered contrast. |
id |
optional allocation-sharing id. Equal ids share compatible allocation weights, not the total-effect prior. For terms with multiple ordered factors, use a named character vector. |
prior_weights |
numeric prior model weight. |
Details
This is RoBMA's re-export of BayesTools::prior_ordered().
Spike-and-slab or mixture behavior belongs on total, e.g.,
prior_ordered(prior_spike_and_slab(...)).
Unsupported ordered combinations raise typed
BayesTools_ordered_unavailable conditions; constructor support does not
imply support for every post-fit operation.
Value
An object inheriting from prior.
See Also
Random-effect prior constructors
Description
Constructors for specifying priors and policies for the random effects in
brma.mv(). These functions are re-exported from BayesTools so a partial or
complete random-effect prior can be written with the RoBMA namespace alone.
prior_random() collects the specification supplied through
prior_heterogeneity. random_block() overrides priors or policies for one
named random-effect block.
random_covariance() supplies correlation priors, with prior_lkj() used
for an unstructured correlation matrix. random_variance_allocation()
distributes an aggregate random-effect standard deviation across blocks or
across the SD components of one heterogeneous block. Its required name is
a stable internal identifier, while display_name and component_names
control public semantic labels. allocation_ref() connects a child
allocation to a component of an earlier named allocation.
random_monitor() controls saved random-effect quantities, and
random_new_levels() controls prediction for previously unseen grouping
levels. random_sd_source() is the advanced adapter for an existing scalar
or row-shaped JAGS node that supplies a random-effect SD without owning a new
prior for that node.
Usage
prior_random(
...,
sd = NULL,
covariance = NULL,
cor = NULL,
monitor = random_monitor(),
new_levels = random_new_levels(),
allocation = NULL,
parameterization = "noncentered"
)
random_block(
sd = NULL,
covariance = NULL,
cor = NULL,
monitor = NULL,
new_levels = NULL,
terms = NULL,
contrasts = NULL,
sd_source = NULL,
parameterization = NULL
)
random_variance_allocation(
name,
terms = NULL,
sd = NULL,
weights = NULL,
parent = NULL,
target = c("block", "sd_component"),
scale = c("total_variance", "mean_variance"),
sd_source = NULL,
inclusion = NULL,
display_name = name,
component_names = NULL
)
allocation_ref(allocation_name, component)
random_covariance(
structure = NULL,
sd = NULL,
cor = NULL,
eta = NULL,
cor_scale = c("fisher_z", "cor", "logit")
)
prior_lkj(eta = 1, include_correlation = TRUE, include_primitives = FALSE)
random_monitor(
latent = TRUE,
coefficients = FALSE,
correlation = TRUE,
lkj_primitives = FALSE
)
random_new_levels(method = c("error", "zero", "sample"))
random_sd_source(source, shape = c("scalar", "row"))
Arguments
... |
named |
sd |
an SD prior with nonnegative support. In |
covariance |
a |
cor |
an optional correlation prior. Use |
monitor |
a |
new_levels |
a |
allocation |
a |
parameterization |
requested sampled representation:
|
terms |
in |
contrasts |
for |
sd_source |
an external SD source created with |
name |
required stable allocation identifier used internally and by
|
weights |
an optional Dirichlet prior over allocation weights. For a
block allocation with explicit |
parent |
an optional |
target |
allocation target: |
scale |
variance normalization. |
inclusion |
an optional named list of scalar probability priors. For a block allocation, each named component receives an independent Bernoulli inclusion gate. |
display_name |
public semantic owner used as the parameter-name prefix.
It defaults to |
component_names |
optional public names for allocation components, in
the same order as |
allocation_name |
name of an earlier allocation referred to by
|
component |
component label within the referenced allocation. Named
allocation |
structure |
optional covariance-family label for
|
eta |
positive LKJ concentration. Values above one increasingly favor
correlations near zero; |
cor_scale |
scale for an explicitly supplied scalar |
include_correlation |
whether |
include_primitives |
whether |
latent |
whether to monitor standardized latent random effects. These are required for bridge sampling and random-coefficient reconstruction. |
coefficients |
whether to monitor realized group-level coefficients. This can be convenient for inspection but memory intensive. |
correlation |
whether semantic correlation matrices are included in monitored output. Scalar structures may retain an internal backend coordinate during sampling and derive the requested correlation matrix afterward. |
lkj_primitives |
whether to retain LKJ primitive beta coordinates for backend inspection. These coordinates remain internal and are not public plotting, density, or hypothesis targets. |
method |
new-level prediction method. |
source |
existing JAGS node name, or a BayesTools |
shape |
source shape for |
Details
Formula structure is separate from prior structure
The random formula owns the grouping variables, coefficient or index
design, and covariance family. These prior constructors configure the
already parsed blocks; they do not reinterpret the formula. The id(),
diag(), and us() / un() families use a coefficient formula: 1, 0,
and -1 control the random intercept, and continuous slopes, factor slopes,
and interactions are supported. Plain | syntax defaults to US and || to
DIAG.
Factor coding in a random-coefficient block is owned by resolved contrast
metadata, not by the presence of an intercept. Existing fixed-factor
contrasts are reused when available; random_block(contrasts = ...) supplies
an explicit block-specific override. Thus us(0 + group | study) combined
with contrasts = c(group = "independent") gives one correlated coefficient
per factor level and no random intercept. Omitting the intercept alone does
not force a level-indicator basis.
The cs() / hcs(), ar1() / ar() / har(), and car() structures
instead own an index basis. Their blocks reject intercept controls and
random_block(contrasts = ...). HCS estimates one common pairwise
correlation; US estimates an unrestricted correlation matrix among the
selected coefficient columns, except within an exchangeable mean-difference
or orthonormal factor unit. See random_effect_formula_tags() for the
full formula and index-type contract.
RoBMA completion of partial specifications
A named random_block() must match the block name produced by the parsed
formula. Use only_priors = TRUE when constructing a brma.mv() object and
then print_prior(object, parameter = "random") to inspect the resolved
names and completed specification. An ordinary positive prior supplied to
prior_heterogeneity changes RoBMA's base heterogeneity prior while retaining
its automatic allocation and covariance rules. A prior_random() object with
no SD or allocation specification is completed in the same way: RoBMA adds
its UISD-scaled base SD and any required Dirichlet allocation while retaining
the supplied block contrasts, covariance priors, and policies. If any global
or block SD, SD source, term-specific SD override, covariance-owned SD, or
allocation is supplied, the user owns the complete scale architecture and
RoBMA does not merge in scale defaults.
Consequently, covariance-only, contrast-only, monitoring-only,
prediction-only, and parameterization-only objects are partial and
self-finishing in
RoBMA. For example,
prior_random(study = random_block(contrasts = c(group = "independent")))
needs no explicit SD, allocation, or LKJ prior for a US block. In contrast,
adding sd = ... makes the object complete; every other required scale or
allocation must then be supplied explicitly.
Standard-deviation and correlation priors
Standard-deviation priors must have nonnegative support. Scalar-correlation
structures use cor in random_covariance(); cor_scale = "fisher_z"
places the prior on Fisher's z, whereas cor_scale = "cor" places it on the
raw correlation. When omitted, CS/HCS receive a uniform prior over
(-1 / (K - 1), 1), AR1/HAR over (-1, 1), and CAR over [0, 1).
Unstructured us() blocks default to prior_lkj(eta = 1). Values of eta
above one shrink correlations toward zero; eta = 1 is uniform over
correlation matrices.
The covariance family remains formula-owned. random_covariance(structure = ...) is mainly useful in direct BayesTools workflows; when used with
brma.mv(), an explicit structure must match the parsed formula family.
Use prior_lkj() as cor for an unstructured matrix prior and an ordinary
scalar prior as cor for a scalar-correlation structure.
Variance allocation
A block allocation with scale = "total_variance" exposes RoBMA quantities
tau_total and tau2_total and splits the slab variance across multiple
random-effect blocks. With optional inclusion gates,
\sigma_j = I_j\sigma_{\mathrm{slab}}\sqrt{w_j}, \qquad
\sigma_{\mathrm{total}}^2 = \sigma_{\mathrm{slab}}^2
\sum_j I_j w_j.
The public tau2_prop(j) is I_j w_j / \sum_k I_k w_k, conditional on
positive total variance. The slab scale and raw weights remain internal.
An SD-component allocation with
scale = "mean_variance" instead exposes tau_common and tau2_common and
gives each component the common-SD scale at equal weights:
\sigma_j = \sigma_{\mathrm{common}}\sqrt{K w_j}, \qquad
K^{-1}\sum_j \sigma_j^2 = \sigma_{\mathrm{common}}^2.
The corresponding public multipliers are tau2_mult(j) = K * w[j] and
tau_mult(j) = sqrt(K * w[j]).
This is useful for heterogeneous level-specific SDs. Root allocations own an
SD prior or external SD source. Child allocations inherit one named parent
component through allocation_ref() and therefore must not supply another
SD source. inclusion optionally places independent Bernoulli gates on
named block-allocation components.
Public parameter names
Random-effect quantities are exposed through the semantic catalog view of
BayesTools' fitted parameter map. Concrete posterior coordinates are a linked
view of the same map and are not additional public names. BayesTools
canonical names use (formula) owner: quantity(arguments) with general
sd, var, and cor terminology. RoBMA maps these to meta-analytic I/O
names: a sole random intercept is tau for a bare block and study: tau for
a named block; a non-intercept coefficient remains explicit, for example
study: tau(x). An owner-free tau is accepted only when it resolves
uniquely. Public RoBMA correlations use rho; compact covariance-construction
coordinates remain internal backend dependencies.
A bare formula or unnamed one-entry list omits a redundant component owner.
An explicitly named one-entry list retains its owner. For multiple
components, public component names come from the formula list; missing names
are generated as component 1, component 2, and so on.
Total-variance allocations expose realized tau_total, tau2_total, and
tau2_prop(...). Mean-variance allocations expose tau_common,
tau2_common, tau2_mult(...), and tau_mult(...).
Monitoring, prediction, and parameterization
Keep the default random_monitor(latent = TRUE) when bridge sampling or
conditional prediction is required. For new grouping levels,
random_new_levels("error") is the safe default; "zero" removes their
random contribution and "sample" draws from the fitted random-effect
distribution.
RoBMA creates external SD sources automatically for its location-scale
random-effect models. Use random_sd_source() directly only when a custom
complete specification intentionally references a JAGS node created elsewhere
in the model being fitted.
parameterization changes only the sampled backend representation.
"noncentered" samples standardized latent effects, "centered" samples
realized group coefficients, and "auto" asks BayesTools to choose from the
resolved design. It does not change any SD, allocation, or correlation
prior. Unsupported centered configurations are rejected; "auto" can fall
back to noncentering.
A named random_block() may instead request "mean_centered" for a sampled
block; the top-level parameterization does not accept it and "auto" never
selects it. It samples the group effects around the compiled contribution of
the fixed terms the block absorbs (the intercept and any moderator its
random-effect design spans or that is constant within its groups, and the
group locations of an enclosing mean-centered block), so the original effect,
SD, allocation, and correlation priors are unchanged; see
BayesTools::prior_random(). A block that absorbs nothing is rejected. The
mode needs the positive SD coordinates of centered blocks and is rejected for
marginalized blocks, known between-group covariance, and selection models in
which the block is integrated rather than retained in the selection
normalizer.
Value
prior_random() returns a prior_random object. The remaining functions
return the corresponding list-like helper objects consumed by
prior_random().
See Also
random_effect_prior_specification(), random_effect_formula_tags(),
prior(), brma.mv()
Examples
sd_prior <- prior(
"normal",
parameters = list(mean = 0, sd = 0.5),
truncation = list(lower = 0, upper = Inf)
)
# One random coefficient per group level, with unrestricted correlation.
random_formula <- ~ us(0 + group | study)
unstructured_prior <- prior_random(
study = random_block(
contrasts = c(group = "independent")
)
)
# The same coefficient basis can instead have a diagonal covariance.
diagonal_formula <- ~ diag(0 + group | study)
diagonal_prior <- prior_random(
study = random_block(
contrasts = c(group = "independent")
)
)
# Correlation-only customization remains partial: RoBMA supplies the SDs.
cor_prior <- prior("normal", list(mean = 0, sd = 1))
hcs_prior <- prior_random(
study = random_block(
covariance = random_covariance(
cor = cor_prior,
cor_scale = "fisher_z"
)
)
)
# Allocate one common SD scale across a block's level-specific SD components.
component_allocation <- random_variance_allocation(
name = "heterogeneity",
display_name = "",
terms = "study",
sd = sd_prior,
weights = prior("dirichlet", list(alpha = c(1, 1))),
target = "sd_component",
scale = "mean_variance"
)
allocated_prior <- prior_random(
study = random_block(
covariance = random_covariance(cor = prior_lkj(eta = 1)),
contrasts = c(group = "independent")
),
allocation = component_allocation
)
# A complete AR prior owns both its SD and its scalar correlation prior.
ar_cor_prior <- prior("normal", list(mean = 0, sd = 0.5))
autoregressive_prior <- prior_random(
study = random_block(
sd = sd_prior,
covariance = random_covariance(
cor = ar_cor_prior,
cor_scale = "fisher_z"
)
)
)
# Monitoring and new-level prediction policies are explicit when customized.
prediction_prior <- prior_random(
sd = sd_prior,
monitor = random_monitor(latent = TRUE, coefficients = FALSE),
new_levels = random_new_levels(method = "sample")
)
# Advanced: refer to an existing row-shaped model node as the SD source.
external_sd <- random_sd_source("tau", shape = "row")
Prior specification
Description
Prior distributions can be supplied for all model parameters. When omitted, the fitting functions construct defaults from the effect-size measure, sample sizes, or informed-prior settings when available.
This typically includes the pooled effect \mu and between-study heterogeneity
\tau. In the case of meta-regression, the pooled effect \mu corresponds to
the intercept, and additional prior distributions for the regression coefficients
are required. In the case of a location-scale model, the between-study heterogeneity
corresponds to the intercept of the scale regression, and additional prior
distributions for the scale regression coefficients are required.
Priors of parameters with a restricted support are truncated to it: priors of
the heterogeneity and of scale intercepts to [0, \infty), priors of the
heterogeneity allocation and of the base rate to [0, 1]. An unbounded
truncation point, such as the default of prior("normal", ...), is moved
to the support boundary with a warning; a finite truncation point outside the
support is an error.
Arguments
prior_effect |
prior distribution for the effect size ( |
prior_heterogeneity |
prior distribution for the heterogeneity ( |
prior_mods |
prior distribution for the moderators ( |
prior_scale |
prior distribution for the scale ( |
prior_heterogeneity_allocation |
prior distribution for the fraction of
heterogeneity allocated to the cluster-level component in multilevel models
( |
prior_baserate |
prior distribution for the estimate-specific midpoint
base-rate probability in binomial GLMM models ( |
prior_lograte |
prior distribution for the estimate-specific midpoint
log-rate in Poisson GLMM models ( |
prior_unit_information_sd |
numeric. The unit information standard deviation ( |
rescale_priors |
numeric. A scaling factor for supported prior distributions.
Point and none priors are unchanged; supplied |
standardize_continuous_predictors |
logical. Whether to standardize continuous predictors.
Defaults to |
set_contrast_factor_predictors |
character. How to set contrast for factor predictors.
Defaults are constructor-specific and shown in each function usage. Single-model
constructors use |
prior_informed_field |
character. The field of the informed prior distributions.
Omit to use the standard default prior specification; explicit |
prior_informed_subfield |
character. The subfield of the informed prior distributions.
Can only be specified together with |
Details
There are several ways to specify the prior distributions:
via a standardized effect size
measurewith known unit information standard deviation,by estimating unit information standard deviation using sample sizes
ni,by manually setting
prior_unit_information_sd,by specifying informed empirical prior distributions via
prior_informed_fieldandprior_informed_subfield,or via fully custom specification using the
prior_effect,prior_heterogeneity,prior_mods,prior_scale, andprior_heterogeneity_allocationarguments.
In all cases, the prior behavior can be further modified by the rescale_priors,
standardize_continuous_predictors, and set_contrast_factor_predictors arguments.
(1) Specifying prior distributions via standardized effect size measures with known
unit information standard deviation
This is the easiest way to specify prior distributions. The width of prior
distributions is based on a fraction of the known unit information standard deviation (UISD)
(Röver et al. 2021). The default prior distributions for the parameters
are set as follows:
| effect size: | Normal(0, \frac{1}{2} UISD) |
| heterogeneity: | Normal+(0, \frac{1}{4} UISD) |
| effect moderation: | Normal(0, \frac{1}{4} UISD) |
| heterogeneity moderation: | Normal(0, \frac{1}{2})
|
The heterogeneity moderation parameters are multiplicative, as such they are independent of UISD.
The default fraction of the UISD can be changed via RoBMA.options() using one of
the following arguments: "default_UISD.effect", "default_UISD.heterogeneity",
"default_UISD.mods", "default_UISD.scale".
The known UISD for standardized effect size measures (measure) are set as follows:
"SMD": | \sqrt{2} |
"ZCOR": | 1 |
"RR": | \sqrt{4} |
"OR": | \sqrt{4} |
"HR": | \sqrt{4} |
"IRR": | \sqrt{4}
|
See Chapter 2.4 in Spiegelhalter et al. (2004) and Chapter 1 in Grieve (2022).
(2) Estimating unit information standard deviation using sample sizes
When effect sizes are on a non-standardized scale (measure = "GEN") or use a
standardized effect size without known UISD, the UISD can be estimated from
sample sizes (ni) and standard errors (sei) following Equation 6 in
Röver et al. (2021). The estimated UISD is then used to
scale the default prior distributions as described in section (1).
Note that the known UISD for standardized effect size measures (section (1)) is
used if available, even when ni is provided.
(3) Manually setting unit information standard deviation
Alternatively, the UISD can be specified directly via the prior_unit_information_sd
argument. This is useful when the appropriate scale for prior distributions is known
a priori or when multiple analyses are to be performed on subsets of the same data
(re-estimating UISD on different subsets of the data can lead to slightly different
prior distributions for different subsets; see estimate_unit_information_sd()).
The specified prior_unit_information_sd is then used to scale the default prior
distributions as described in section (1).
Note that the manually specified prior_unit_information_sd takes precedence over
the estimated UISD from ni (section (2)) and the known UISD from measure
(section (1)). It cannot be combined with prior_informed_field.
(4) Specifying informed empirical prior distributions
Informed prior distributions can be specified via the prior_informed_field and
prior_informed_subfield arguments. Currently, only prior_informed_field = "medicine"
with subfields defined in BayesTools::prior_informed_medicine_names is supported,
which uses empirically derived prior distributions from medical meta-analyses as described in
Bartoš et al. (2021) and
Bartoš et al. (2023).
When prior_informed_field = "medicine", the default prior_informed_subfield is
"Cochrane" (i.e., using the whole CDSR database as a reference). The informed
prior distributions are available for the following effect size measures:
"SMD": | standardized mean difference |
"OR": | log odds ratio |
"RR": | log risk ratio |
"RD": | risk difference |
"HR": | log hazard ratio |
Note that informed prior distributions are only available for the effect size (\mu)
and heterogeneity (\tau) parameters. For effect moderation (prior_mods), the
informed effect prior is scaled by a factor of RoBMA.get_option("default_informed_priors.mods").
For heterogeneity moderation (prior_scale), a normal prior with standard deviation
specified by RoBMA.get_option("default_informed_priors.scale") is used.
(5) Fully custom prior distributions
Prior distributions can be fully customized by directly specifying the prior_effect,
prior_heterogeneity, prior_mods, prior_scale, and prior_heterogeneity_allocation
arguments. These should be prior distribution objects created via BayesTools::prior()
or related functions (e.g., prior_factor()).
For brma.mv() random-effect formulas, see
random_effect_prior_specification.
Rescaling prior distributions
The rescale_priors argument allows rescaling supported prior distributions by a
multiplicative factor. For example, rescale_priors = 2 doubles the standard
deviations/scales of normal, Cauchy, t, and inverse-gamma prior distributions,
making them more diffuse. Point and none priors are unchanged. For publication-bias
prior distributions, see publication_bias_prior_specification.
References
Bartoš F, Gronau QF, Timmers B, Otte WM, Ly A, Wagenmakers E (2021).
“Bayesian model-averaged meta-analysis in medicine.”
Statistics in Medicine, 40(30), 6743–6761.
doi:10.1002/sim.9170.
Bartoš F, Otte WM, Gronau QF, Timmers B, Ly A, Wagenmakers E (2023).
“Empirical prior distributions for Bayesian meta-analyses of binary and time-to-event outcomes.”
doi:10.48550/arXiv.2306.11468.
Preprint available at https://doi.org/10.48550/arXiv.2306.11468.
Grieve AP (2022).
Hybrid frequentist/Bayesian power and Bayesian power in planning clinical trials.
Chapman and Hall/CRC.
Röver C, Bender R, Dias S, Schmid CH, Schmidli H, Sturtz S, Weber S, Friede T (2021).
“On weakly informative prior distributions for the heterogeneity parameter in Bayesian random-effects meta-analysis.”
Research Synthesis Methods, 12(4), 448–474.
doi:10.1002/jrsm.1475.
Spiegelhalter DJ, Abrams KR, Myles JP (2004).
Bayesian approaches to clinical trials and health-care evaluation.
John Wiley and Sons.
doi:10.1002/0470092602.
See Also
publication_bias_prior_specification,
random_effect_prior_specification,
prior, RoBMA.options,
brma
Weightfunction Prior
Description
Create weightfunction publication-bias priors and their weight-prior helper objects.
Usage
prior_weightfunction(
side = "one-sided",
steps = c(0.025, 0.05),
weights = wf_cumulative(),
reference = "most_significant",
prior_weights = 1,
model = selection_model()
)
wf_cumulative(alpha = NULL)
wf_fixed(omega)
wf_independent(prior, scale = "omega")
Arguments
side |
character. Either |
steps |
numeric vector of p-value cut points. These define
|
weights |
a weight-prior object created by |
reference |
character. Reference bin, currently
|
prior_weights |
numeric prior model weight. |
model |
fixed likelihood choices from |
alpha |
optional positive cumulative-Dirichlet concentration parameters,
one per p-value bin. If |
omega |
fixed publication weights, one per bin; values must be
non-missing, nonnegative, and match |
prior |
continuous simple prior distribution for each non-reference weight. Point, discrete, mixture, and other non-simple priors are invalid. |
scale |
latent scale for independent weights; either |
Details
Fixed weights must have one value per p-value bin
(length(steps) + 1), and the reference bin must have weight 1.
Value
prior_weightfunction() returns an object inheriting from
prior and prior.weightfunction; the wf_*() helpers
return weightfunction_weights helper objects with subclass markers.
See Also
publication_bias_prior_specification
Examples
prior_weightfunction("one-sided", steps = 0.025)
prior_weightfunction(
side = "one-sided",
steps = c(0.025, 0.5),
weights = wf_fixed(c(1, 0.8, 0.6))
)
Publication-bias prior specification
Description
Publication-bias prior distributions are specified separately from the
meta-analytic prior distributions documented in
prior_specification. They define selection-model weights,
PET/PEESE regression coefficients, or the publication-bias model space in
RoBMA and RoBMA.mv.
Arguments
prior_bias |
prior distribution for publication-bias adjustment. For
|
prior_bias_null |
prior distribution(s) for null publication-bias
component(s) in |
model_type |
character string specifying predefined publication-bias
model ensembles for |
steps |
numeric vector of one-sided p-value cut points for the default
|
Details
Single-model bias-adjustment priors
bselmodel, bselmodel.mv, bPET,
bPET.mv, bPEESE, and bPEESE.mv
fit one publication-bias adjustment at a time. The prior_bias
argument must match the fitted bias-adjustment type.
| Constructor | Prior constructor | Default prior distribution |
bselmodel() | prior_weightfunction | one-sided cumulative weightfunction with steps = 0.025 |
bPET() | prior_PET | positive Cauchy centered at 0 |
bPEESE() | prior_PEESE | positive Cauchy centered at 0, with UISD-adjusted scale |
bPET.mv() | prior_PET | same as bPET() |
bPEESE.mv() | prior_PEESE | same as bPEESE()
|
The default PET prior distribution uses
RoBMA.get_option("default_bias_PET.scale"). The default PEESE prior
distribution uses RoBMA.get_option("default_bias_PEESE.scale") after
rescaling to the analyzed effect-size measure. The default weightfunction
prior distribution uses RoBMA.get_option("default_bias_weightfunction.alpha")
for each cumulative-Dirichlet alpha parameter.
Model-averaged publication-bias priors
RoBMA and RoBMA.mv average over
publication-bias components. By default, prior_bias_null is
prior_none() and model_type determines the alternative
components:
"PSMA" | six weight functions, PET, and PEESE |
"6w" | six weight functions |
"2w" | two two-sided weight functions |
"PP" | PET and PEESE |
Custom prior_bias replaces the preset alternative components. If
prior_bias is omitted, model_type still supplies the default
alternative components even when prior_bias_null is customized or
omitted. Setting prior_bias = NULL or prior_bias = FALSE
omits all alternative bias-adjustment models. Setting
prior_bias_null = NULL or prior_bias_null = FALSE omits the
no-bias component.
Each publication-bias component has a prior model weight. User-specified
components receive equal weights unless their prior objects set
prior_weights. The "2w" and "6w" presets split the
alternative bias mass equally across their weight functions, "PP"
splits it equally across PET and PEESE, and "PSMA" assigns half of the
alternative bias mass to the six weight functions combined and one quarter
each to PET and PEESE.
Publication-bias prior distributions are not rescaled by rescale_priors.
The exception is the default PEESE prior distribution, whose scale is adjusted
to the effect-size measure via the unit-information standard deviation.
See Also
prior_weightfunction, prior_PET,
prior_PEESE, prior_none,
RoBMA_prior_specification,
prior_specification
Normal QQ Plot for brma Object
Description
qqnorm.brma creates a normal QQ plot for a fitted brma
object. The plot displays sorted standardized residuals on the vertical axis
against the theoretical quantiles of a standard normal distribution on the
horizontal axis. Under a correctly specified model, the points should fall
approximately along the diagonal reference line.
Usage
## S3 method for class 'brma'
qqnorm(
y,
type = "rstudent",
unit = "estimate",
conditioning_depth = "marginal",
envelope = TRUE,
conf_level = 95,
bonferroni = FALSE,
reps = 1000,
smooth = TRUE,
xlim,
ylim,
xlab,
ylab,
plot_type = "base",
max_samples = Inf,
...
)
Arguments
y |
a fitted brma object. |
type |
the type of standardized residuals to use. Options are:
|
unit |
output unit. Only |
conditioning_depth |
residual conditioning depth. Options are
|
envelope |
logical indicating whether to add a pseudo confidence
envelope to the plot. The deterministic envelope uses Beta order-statistic
quantiles transformed to the standard normal scale, providing a reference
under a correctly specified model. Defaults to |
conf_level |
finite numeric value strictly between 0 and 100 specifying the confidence level
for the envelope bounds. Defaults to |
bonferroni |
logical indicating whether to apply Bonferroni correction
to the envelope, so it can be regarded as a simultaneous confidence region
for all |
reps |
retained for compatibility with earlier simulation-based envelopes. The current envelope is deterministic and does not use this argument. |
smooth |
logical indicating whether to smooth the envelope bounds using
Friedman's SuperSmoother ( |
xlim |
x-axis limits. If not specified, limits are computed from data. |
ylim |
y-axis limits. If not specified, limits are computed from data. |
xlab |
title for the x-axis. If not specified, defaults to
|
ylab |
title for the y-axis. If not specified, defaults to
|
plot_type |
whether to use a base plot |
max_samples |
maximum posterior draws used to compute known- |
... |
additional graphical arguments to customize the plot appearance:
|
Details
The normal QQ plot is a diagnostic tool for assessing whether the
standardized residuals follow a standard normal distribution, as expected
under a correctly specified model. Each point represents one estimate,
plotted at coordinates (\Phi^{-1}(p_i), z_{(i)}) where
p_i are the plotting positions and z_{(i)} are the sorted
standardized residuals.
Each retained input row contributes one point, irrespective of its likelihood
weight. Weights affect fitting and the residual calculation; they do not
replicate points or multiply residual values in this plot.
The default residual type is "rstudent" (LOO-PIT), which differs
from metafor::qqnorm (which defaults to "rstandard").
LOO-PIT residuals are preferred for normal outcome models because they
properly account for
estimation uncertainty via leave-one-out cross-validation.
The confidence envelope is computed in closed form from the distribution of
normal order statistics. For the i-th sorted residual,
\Phi(Z_{(i)}) follows a beta distribution with shape parameters
i and k + 1 - i. Pointwise quantile bounds are transformed back
with \Phi^{-1}. When smooth = TRUE, bounds are smoothed using
Friedman's SuperSmoother. When bonferroni = TRUE, the confidence
level is adjusted for simultaneous inference across all k comparisons.
For correlated known-V brma.mv() "rstandard" residuals,
this envelope remains an independent order-statistic reference band. It is
descriptive and does not model residual correlation induced by known sampling
covariance.
For binomial and Poisson GLMMs the LOO-PIT residuals are a descriptive normal
approximation on the effect-size scale rather than a PIT of the fitted
discrete likelihood (see residuals.brma); the default
y-axis label says so.
Value
For plot_type = "base", returns an invisible list with
components x (theoretical quantiles) and y (sorted
residuals). For plot_type = "ggplot", returns a ggplot object.
If as_data = TRUE, returns a list with all computed plot data
including: x, y, points, refline,
envelope, xlim, ylim, xlab, and ylab.
See Also
rstudent.brma(), rstandard.brma(), residuals.brma(),
funnel.brma(), radial.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
fit <- add_loo(fit)
qqnorm(fit)
qqnorm(fit, type = "rstandard")
qqnorm(fit, envelope = FALSE)
qqnorm(fit, plot_type = "ggplot")
qqnorm(fit, pch = 19, col = "blue", shade = "lightblue")
}
## End(Not run)
Radial (Galbraith) Plot for brma Object
Description
radial.brma creates a radial (Galbraith) plot for a
fitted brma object. The plot displays each study as a point with
precision on the x-axis and the standardized effect size on the z-axis.
Without centering, a line from the origin through any point has slope equal
to the observed effect size. With centering, slopes are relative to the
pooled estimate. An arc on the right side maps standardized values back to
the effect size scale.
Usage
## S3 method for class 'brma'
radial(
x,
center = FALSE,
xlim,
zlim,
xlab,
zlab,
atz,
aty,
steps = 7,
level = 95,
digits = 2,
transf,
targs,
plot_type = "base",
...
)
## S3 method for class 'brma'
galbraith(x, ...)
Arguments
x |
a fitted brma object. Must be an intercept-only model (no moderators or scale regression). |
center |
logical indicating whether to center the plot at the
pooled estimate. When |
xlim |
x-axis limits. If not specified, limits are computed from data. |
zlim |
z-axis limits. If not specified, limits are computed from data. |
xlab |
title for the x-axis. If not specified, a default label is used. |
zlab |
title for the z-axis. If not specified, a default label is used. |
atz |
numeric vector of positions for tick marks on the z-axis (left vertical axis). If not specified, positions are chosen automatically. |
aty |
numeric vector of effect size values to mark on the y-axis arc (right side). If not specified, values are chosen automatically. |
steps |
integer specifying the number of tick marks on the y-axis arc
when |
level |
numeric value between 0 and 100 specifying the confidence level
for the confidence band and pooled-effect CI arc. Defaults to |
digits |
integer specifying the number of decimal places for y-axis
arc labels. Defaults to |
transf |
optional transformation function applied to the y-axis arc
labels (e.g., |
targs |
optional list passed to |
plot_type |
whether to use a base plot |
... |
additional graphical arguments to customize the plot appearance:
|
Details
The radial (Galbraith) plot transforms each study's effect size and standard error into a point in precision-standardized space:
x-axis: precision =
1/\sqrt{v_i + \hat{\tau}_i^2}z-axis: standardized effect =
y_i/\sqrt{v_i + \hat{\tau}_i^2}
For ordinary and specialized multilevel models, the marginal heterogeneity
is common and \hat{\tau}_i = \hat{\tau}. Random-formula models use
each row's marginal random-effect standard deviation. Known sampling
covariance uses its diagonal for v_i; plotted points can therefore be
dependent.
For a single normal model, the sloped parallelogram is the usual marginal
Gaussian reference band around the pooled-effect line. For GLMMs it is a
continuity-corrected effect-size approximation; for selection, PET/PEESE,
and product-space models it remains a bias-adjusted posterior-mean reference
rather than an exact envelope of the fitted observation law. The arc on the
right side allows reading individual effect sizes by projecting from the
origin through a point to the arc; when center = TRUE, the plotted
slope is relative to the pooled effect.
This function requires an intercept-only model without scale regression or likelihood weights. Likelihood-weighted fits do not have a single radial precision target because the observational variance and power-likelihood information scales differ.
galbraith() is a same-argument alias for radial().
Value
radial.brma returns NULL invisibly if
plot_type = "base" or a ggplot object if plot_type = "ggplot".
If as_data = TRUE, returns a list with the computed plot data
including: points, refline, band, arc,
arc_ticks, ci_arc, ci_ticks, xlim, and
zlim. Returned arc coordinates use plain trigonometry; both renderers
recompute arcs for their aspect ratio, so the data do not encode final device geometry.
References
Galbraith, R. F. (1988). Graphical display of estimates having differing standard errors. Technometrics, 30(3), 271-281.
Galbraith, R. F. (1994). Some applications of radial plots. Journal of the American Statistical Association, 89(428), 1232-1242.
See Also
funnel.brma(), pooled_effect.brma(), pooled_heterogeneity.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(yi = yi, vi = vi, data = dat, measure = "RR")
radial(fit)
radial(fit, center = TRUE)
radial(fit, plot_type = "ggplot")
galbraith(fit)
}
## End(Not run)
Random-Effect Formula Structure Tags
Description
brma.mv() random-effect formulas use BayesTools random-effect formula
structure tags to describe the covariance structure of random coefficients.
These tags are formula specials parsed by
BayesTools::random_effects_formula(), not ordinary user-facing functions.
Details
Use tags as bare names inside the random formula supplied to brma.mv(),
for example random = ~ cs(comp | study).
They are parsed from the formula call and are not called as normal R
functions, so users should not write RoBMA::cs() or BayesTools::cs().
RoBMA forwards the formula to BayesTools::random_effects_formula(), stores
the parsed BayesTools random-effect metadata, and uses that metadata for
JAGS compilation, prior matching, prediction, and summary labels.
BayesTools distinguishes random-coefficient formulas from structured index
specifications. For id(), diag(), and us() / un(), the left side of
| is a coefficient formula. It can contain an intercept, continuous or
factor slopes, and interactions. As in an ordinary random-slope formula,
1, 0, and -1 include or remove the random intercept. Plain
(expr | group) defaults to us(expr | group), while expr || group is the
diagonal shorthand.
Factor coding inside a random-coefficient block is not selected by removing
the intercept. BayesTools reuses an already established fixed-factor
contrast by default and lets a
random_block set an explicit block-specific basis through
contrasts. For example, us(0 + group | study) together with
random_block(contrasts = c(group = "independent")) creates one correlated
random coefficient per group level and no random intercept. Without the
independent contrast override, 0 + group preserves the resolved contrast
basis instead of forcing raw level indicators.
In contrast, cs(), hcs(), ar1() / ar(), har(), and car() own a
structure-specific index basis. Their left side names index columns rather
than coefficients. These tags reject explicit 1, 0, and -1, and their
blocks do not accept random_block(contrasts = ...).
Supported structure tags:
-
id(): independent random-coefficient columns with one shared standard deviation. -
diag(): independent random-coefficient columns with one standard deviation per column.||is shorthand for this structure. -
us()/un(): one standard deviation per random-coefficient column and an unrestricted correlation matrix. Plain|syntax defaults to this structure. -
cs(): compound symmetry over one or more discrete index columns; index levels share one standard deviation and one common pairwise correlation. -
hcs(): heterogeneous compound symmetry over one or more discrete index columns; levels have separate standard deviations and one common pairwise correlation. -
ar1()/ar(): homogeneous autoregressive order-1 covariance over exactly one discrete index; levels share one standard deviation and correlations decay as\mathrm{cor}^{|i-j|}over the resolved order. -
har(): heterogeneous autoregressive order-1 covariance; index levels have separate standard deviations and AR(1) correlations. -
car(): continuous-time autoregressive covariance; use exactly one finite numeric/integer coordinate or an ordered factor with numeric level labels, as incar(time | study). Correlations are\mathrm{cor}^dbased on actual absolute distances, and\mathrm{cor}is constrained to[0, 1). -
random()/re(): explicit random-effect block wrapper. By default this uses an unstructured covariance, and it can be useful when specifying an explicitnamefor prior matching and summaries.
Under diag(), us(), and plain bars, the contrast columns of a
mean-difference or orthonormal factor term are one exchangeable unit: they
share one standard deviation and are uncorrelated with each other, while
us() keeps the unit's correlations with the other columns. A us() block
that is a single such unit therefore has no correlation parameter, and a
us() block cannot hold two such terms with three or more levels.
The discrete structured tags cs(), hcs(), ar1(), and har() accept
factor, character, numeric/integer, or logical index columns. Existing factor
level order is retained; otherwise sorted unique values determine the levels
and, for AR(1), their order. cs() and hcs() may combine multiple columns
with +; BayesTools forms the observed interaction in lexicographic order.
ar1() and har() require exactly one index column.
AR1/HAR warns when numeric labels in a character or unordered factor resolve
to a non-increasing numeric order, such as 1, 10, 2, while preserving that
order. Use numeric values for numeric ordering, or an ordered factor with
explicit levels to confirm another intended order.
hcs(index | group) and us(0 + index | group) are different models even
when both produce one standard deviation per displayed level. HCS constrains
every pair to the same correlation. US estimates an unrestricted correlation
matrix among the selected coefficient columns and its factor basis must be
specified through contrast metadata when it matters.
Alias tags are normalized before model compilation: un() to us(),
ar() to ar1(), and unqualified random() / re() to us() unless a
covariance override changes the structure.
In these wrappers, covariance = "cs", hom = FALSE resolves to hcs(),
and covariance = "ar1", hom = FALSE resolves to har(). Any explicit
covariance structure in prior_random() must match the resolved structure.
Direct cs() / ar1() tags retain their homogeneous meaning.
brma.mv() also accepts metafor-style known group covariance through its
R and Rscale arguments. This covariance is attached to random-effect
grouping levels and is distinct from the known sampling covariance V.
RoBMA translates R internally to BayesTools random-effect group covariance
metadata; users should continue to use R/Rscale in brma.mv() rather
than BayesTools-native group_covariance arguments. Current support is
limited to random-intercept blocks such as random = ~ 1 | study. Supported
one-to-one known-R blocks in known-V normal models can be compiled as
marginalized diagonal row-variance terms; other supported known-R blocks
remain sampled.
The scalar-correlation structures cs(), hcs(), ar1() / ar(),
and har() use uniform defaults over their complete valid raw-correlation
intervals: (-1 / (K - 1), 1) for CS/HCS and (-1, 1) for AR1/HAR, where
K is the number of resolved index levels. CAR uses Uniform(0, 1) because
its correlation-decay parameter is one-sided. These defaults therefore do
not silently exclude negative correlations when the structure permits them.
A list of formulas defines top-level random-effect components:
random = list( study = ~ cs(comp | study), design = ~ cs(comp | design) )
A bare formula or unnamed one-entry list has no redundant user-facing
component prefix. An explicitly named one-entry list retains its name. In a
list with two or more formulas, missing names are generated as
component 1, component 2, and so on. These component names are used by
RoBMA summaries and by component-specific scale models.
Explicit name = arguments inside random() or re() define the final
random-effect block name used by prior_random() block
overrides.
Public parameter names
BayesTools stores concrete coordinates, selectable semantic quantities, and
aliases in one versioned parameter map. Its canonical random-effect names
use (formula) owner: quantity(arguments). RoBMA maps these to meta-analytic
I/O names: a sole random intercept is tau for a bare block and
study: tau for a named block, while a non-intercept coefficient remains
explicit, for example study: tau(x). The owner-free tau shorthand is
accepted only when it resolves uniquely. Bare formulas and unnamed one-entry
lists omit a redundant owner; explicitly named one-entry lists and
multi-component models retain it.
Public correlations are named rho. Automatic total-variance allocations
expose tau_total, tau2_total, and tau2_prop(...). Mean-variance
allocations within heterogeneous blocks expose tau_common, tau2_common,
tau2_mult(...), and tau_mult(...). BayesTools' general names and compact
covariance-construction coordinates remain internal to RoBMA. These
meta-analytic names are the supported selectors for summaries, plotting,
density estimation, and hypotheses.
See Also
brma.mv(), random_effect_prior_specification,
prior_random, random_covariance,
BayesTools::random_effects_formula()
Examples
## Not run:
fit <- brma.mv(
yi = yi,
V = V,
random = ~ cs(outcome | study),
data = dat,
measure = "GEN",
prior_unit_information_sd = 1
)
fit_network <- brma.mv(
yi = yi,
V = V,
random = list(
study = ~ cs(comp | study),
design = ~ cs(comp | design)
),
data = dat,
measure = "OR"
)
group_prior <- prior_factor(
distribution = "normal",
parameters = list(mean = 0, sd = 1),
contrast = "independent"
)
random_prior <- prior_random(
study = random_block(
contrasts = c(group = "independent")
)
)
fit_group <- brma.mv(
yi = yi, V = V, ni = ni,
mods = ~ 0 + group,
random = ~ us(0 + group | study),
prior_mods = group_prior,
prior_heterogeneity = random_prior,
data = dat, measure = "GEN",
prior_unit_information_sd = 1
)
## End(Not run)
Random-effect prior specification
Description
Random-effect prior distributions are used by brma.mv when a
random formula is supplied. The formula and the prior have deliberately
separate roles. The formula defines the random-effect design, grouping
variables, and covariance family. The prior_heterogeneity argument defines
the prior scale and can additionally customize correlations, variance
allocation, monitoring, prediction, and computational parameterization.
RoBMA constructs a complete random-effect prior when
prior_heterogeneity is omitted. An ordinary positive prior distribution
changes only the base random-effect standard-deviation prior. A
prior_random object can either customize selected non-scale
settings while inheriting RoBMA's scale defaults, or explicitly own the
complete scale architecture.
Arguments
random |
an optional formula or list of formulas specifying
BayesTools random-effect terms for |
prior_heterogeneity |
prior distribution for residual heterogeneity.
In random-formula |
scale |
an optional formula or named list of formulas specifying
location-scale predictors. With random-effect formulas, |
prior_scale |
prior distribution for scale-regression coefficients.
A single prior applies to all terms; a named list can specify term-specific
priors. If omitted or |
prior_unit_information_sd |
numeric. The unit information standard deviation used to construct the default base heterogeneity prior distribution. |
rescale_priors |
numeric. A scaling factor for supported prior distributions. It rescales the base heterogeneity prior distribution before RoBMA constructs the random-effect prior specification. |
Details
Division of responsibility
The random-effect setup has three layers:
| Input | Controls | Does not redefine |
random | blocks, grouping, coefficient/index basis, covariance family | prior scale or prior family |
ordinary prior_heterogeneity | base or aggregate random-effect SD prior | formula structure or automatic allocation |
prior_random(...) | block overrides, covariance priors, allocation, and policies | the structure parsed from random
|
Plain (expr | group) syntax and us() / un() define unstructured
random-coefficient blocks. || and diag() define independent
random-coefficient blocks, while id() gives independent coefficients one
shared SD. In these families, 1, 0, and -1 control the random intercept;
continuous slopes, factor slopes, and interactions are supported. Factor
coding comes from the resolved contrast metadata, not from intercept syntax.
Use random_block(contrasts = ...) when a block-specific factor basis is
required.
The cs(), hcs(), ar1() / ar(), har(), and car() families instead
own a structure-specific index basis. Their left side supplies index
variables rather than a coefficient formula, so these structures reject
intercept controls and block contrast overrides. See
random_effect_formula_tags for the complete formula and
variable-type contract.
Nested grouping syntax, such as random = ~ 1 | study / esid, creates
multiple blocks. A formula list creates top-level components:
random = list( study = ~ 1 | study, outcome = ~ 1 | outcome )
A bare formula or unnamed one-entry list has no redundant public component
prefix. An explicitly named one-entry list retains its name. In lists with
two or more entries, missing names become component 1, component 2, and
so on. Component names are used by summaries and by component-specific
scale models. Block overrides in prior_random() must match the resolved
block names, which can be inspected with
print_prior(object, parameter = "random").
Default standard-deviation prior
RoBMA first constructs the same base heterogeneity SD prior described in
prior_specification. Under the standard UISD defaults,
\sigma_{\mathrm{base}} \sim
\mathrm{Normal}^{+}(0, \mathrm{UISD}/4).
The scale multiplier can be changed through
RoBMA.options(default_UISD.heterogeneity = ...). The same measure, ni,
prior_unit_information_sd, informed-prior, and rescale_priors rules used
for ordinary heterogeneity apply before the prior is assigned to the
random-effect structure.
Supplying an ordinary positive prior through prior_heterogeneity replaces
this base prior only. RoBMA still determines whether it applies directly to
one SD, to the RoBMA quantity tau_total for a total-variance allocation, or
to tau_common for a mean-variance allocation.
Structure-specific defaults
Let K denote the resolved number of random-coefficient columns for a
coefficient structure or the number of index levels for an index structure.
The formula family determines the number of marginal SDs and the default
correlation prior:
| Structure | Basis | Marginal SDs | Default correlation prior |
id() | coefficients | one shared SD | none |
diag() or || | coefficients | one per column or factor unit | none |
plain |, us() / un() | coefficients | one per column or factor unit | LKJ(1) matrix |
cs() | index levels | one shared SD | Uniform(-1 / (K - 1), 1) on raw cor |
hcs() | index levels | one per level | Uniform(-1 / (K - 1), 1) on raw cor |
ar1() / ar() | ordered index | one shared SD | Uniform(-1, 1) on raw cor |
har() | ordered index | one per level | Uniform(-1, 1) on raw cor |
car() | numeric coordinates | one shared SD | Uniform(0, 1) on raw cor, supported on [0, 1)
|
A mean-difference or orthonormal factor term (the default coding of factor
moderators in model-averaging constructors) is one exchangeable unit: its
contrast columns share one SD, tau(f), and are uncorrelated, so the model
of the level deviations does not depend on the arbitrary contrast basis.
Under us() the unit keeps its correlations with the other coefficients,
reported per level (rho(intercept, f[a])) and as the multiple
correlation rho_total(intercept, f); a us() block can hold at most one
such term with three or more levels. SD-component allocations count units,
not columns: K below is the number of SD components.
Correlation priors are added after the formula basis and K are
resolved, and only when the block has more than one random coefficient. The
CS/HCS lower bound is the exact positive-definiteness bound, so the default
includes all admissible negative correlations. LKJ(1) is uniform over
correlation matrices and does not favor positive correlations. In
particular, hcs(index | group) has one common pairwise correlation, while
us(0 + index | group) can estimate a different correlation for every pair
of resolved coefficient columns outside an exchangeable factor unit.
Automatic variance allocation
RoBMA uses symmetric Dirichlet(1, ..., 1) priors whenever a variance scale
must be divided. The allocation is hierarchical when the formula contains
multiple top-level components, nested blocks, or heterogeneous blocks:
A single homogeneous block receives the base SD prior directly.
A split across blocks or components uses
scale = "total_variance". For child weightw_j,\sigma_j = \sigma_{\mathrm{total}}\sqrt{w_j}, \qquad \sum_j \sigma_j^2 = \sigma_{\mathrm{total}}^2.The public aggregate quantities are
tau_totalandtau2_total; components aretau2_prop(...).A heterogeneous block, such as DIAG, US, HCS, or HAR with
K > 1, adds an SD-component allocation withscale = "mean_variance":\sigma_j = \sigma_{\mathrm{common}}\sqrt{K w_j}, \qquad K^{-1}\sum_j \sigma_j^2 = \sigma_{\mathrm{common}}^2.The public aggregate quantities are
tau_commonandtau2_common; components aretau2_mult(...)andtau_mult(...).
Without component-specific scale models, the base prior controls a shared
total or average variance scale. Component-specific or partial scale
models instead create independent roots for the targeted components; every
unscaled component retains its own base SD prior. Splits remain within each
component, so their combined variance is not governed by one global total prior.
Public random-effect parameter names
BayesTools stores concrete coordinates, semantic quantities, and aliases in
one versioned parameter map. RoBMA summaries, plots, density estimation, and
hypotheses use its semantic catalog view.
BayesTools canonical random-effect names have the form
(formula) owner: quantity(arguments). RoBMA consistently maps these to
meta-analytic names: a sole intercept is tau for a bare block and
study: tau for a named block, while a non-intercept coefficient remains
explicit, for example study: tau(x). The unique owner-free shorthand tau
is accepted when only one component matches. Bare formulas and unnamed
one-entry lists omit a redundant owner; explicitly named one-entry lists and
multi-component models retain owners for disambiguation. Other examples are
rho(group[sensitivity],group[specificity]), tau_total, tau_common, and
tau2_prop(study).
A custom random_variance_allocation() always requires a stable internal
name; its display_name and component_names separately control these
public owner and component labels.
Formula-random correlations are public rho quantities. BayesTools'
general cor quantities, compact scalar correlation coordinates, and LKJ
primitives remain internal to RoBMA. In the specialized cluster interface,
rho remains the public variance-allocation and induced intracluster
correlation parameter described in prior_specification.
Ways to customize random-effect priors
There are three increasingly explicit customization levels:
Supply an ordinary positive prior distribution to
prior_heterogeneity. This changes the base SD prior but preserves all automatic allocations and default correlation priors.Supply a partial
prior_random()object containing only correlation, contrast, monitoring, new-level prediction, or parameterization settings. RoBMA supplies its base SD prior and every required variance allocation.Supply a
prior_random()object containing scale architecture. The object is complete and RoBMA does not add or merge scale defaults.
A prior_random() object is partial only when all scale-defining fields are
absent. The following fields make it complete: top-level or block-specific
sd; random_covariance(sd = ...); block sd_source; block terms
containing term-specific SD overrides; or allocation. Once any of these is
present, the user owns the entire scale architecture and must provide every
required SD or allocation source.
For example, the following partial specification changes only the factor
basis of block study:
random_prior <- prior_random( study = random_block(contrasts = c(group = "independent")) )
Combined with random = ~ us(0 + group | study), this creates one
correlated random coefficient per group level. RoBMA supplies the
UISD-scaled common-SD prior and mean-variance Dirichlet allocation; BayesTools adds
the default LKJ(1) correlation prior after resolving the coefficient count.
No empty random_covariance() or manual allocation is needed.
A correlation-only customization is partial as well. Use
random_covariance(cor = prior_lkj(...)) for US/UN and
random_covariance(cor = ..., cor_scale = ...) for CS/HCS, AR1/HAR, or CAR.
An explicitly supplied scalar cor prior defaults to the Fisher-z scale;
cor_scale = "cor" instead places it directly on the raw correlation, and
cor_scale = "logit" uses a logit transform of the structure's admissible
interval. The structure in the formula remains authoritative, and a
conflicting covariance override is rejected.
Complete specifications can define global SD defaults, block-specific
random_block settings, term-specific SDs, external SD sources,
and allocations built with random_variance_allocation. Use a
complete specification when the desired scale hierarchy differs from
RoBMA's automatic total/mean-variance allocation; do not add an SD merely to
customize a correlation or contrast.
The parameterization argument and block-specific overrides select
"noncentered", "centered", or "auto" backend representations without
changing the specified standard-deviation, allocation, or correlation prior
distributions. Explicit centering requires strictly positive backend-owned
standard-deviation coordinates; BayesTools rejects unsupported centered
combinations and lets "auto" fall back to the noncentered representation.
Monitoring and new-level prediction settings similarly affect saved
quantities and prediction policy, not the statistical prior. Keep latent
effects monitored when bridge sampling or conditional prediction is needed.
See prior_random for every constructor argument and complete
examples.
Location-scale random-effect models
When scale is used together with random, the scale model targets the
row-wise total random-effect standard deviation. With one top-level
random-effect component, a single scale formula is unambiguous. With
multiple top-level random-effect components, scale must be a named list
whose names identify the targeted components or concrete blocks. Each
target has its own row-wise SD root and its allocations split within that
component; untargeted components retain independent base SD roots. The
prior_scale argument controls the scale-regression
coefficients. A custom prior_random() containing explicit SD architecture
must agree with these row-shaped scale sources; incompatible sources are
rejected rather than silently replaced.
Inspecting the resolved priors
The completed prior depends on the resolved formula columns and index levels.
Use only_priors = TRUE to perform data, formula, and prior resolution
without MCMC, then inspect the result with
print_prior(object, parameter = "random"). The printed object shows the
resolved block names, SD sources, allocation hierarchy, correlation priors,
contrasts, and policies that will be used for fitting. Its mathematical
sigma_total and sigma_common labels describe the prior architecture;
fitted RoBMA selectors use tau_total and tau_common, respectively.
See Also
prior_specification,
random_effect_formula_tags,
brma.mv,
prior_random,
random_block,
random_covariance,
random_variance_allocation
Examples
## Not run:
dat <- data.frame(yi = c(0.1, 0.2, 0.3, 0.4),
ni = rep(40, 4), study = rep(c("a", "b"), each = 2),
group = factor(rep(c("control", "treatment"), 2)))
V <- diag(rep(0.04, nrow(dat)))
group_prior <- prior_factor("normal", list(0, 1), contrast = "independent")
random_prior <- prior_random(
study = random_block(contrasts = c(group = "independent"))
)
priors <- brma.mv(
yi = yi, V = V, ni = ni,
mods = ~ 0 + group,
random = ~ us(0 + group | study),
prior_mods = group_prior,
prior_heterogeneity = random_prior,
data = dat, measure = "GEN",
only_priors = TRUE
)
print_prior(priors, parameter = "random")
## End(Not run)
Random Effects
Description
Extracts the estimated random effects (deviations from the fixed-effect predictions) from a fitted model.
Usage
ranef(object, ...)
Arguments
object |
a fitted model object |
... |
additional arguments passed to methods |
Value
Method-specific return value, typically posterior samples of the random effect deviations.
See Also
Random Effects for brma Objects
Description
Extracts random effect deviations from a fitted brma object.
These are posterior-sample offsets from the fixed-effect predictions,
analogous to random-effect deviations returned by metafor::ranef().
Usage
## S3 method for class 'brma'
ranef(
object,
bias_adjusted = FALSE,
probs = c(0.025, 0.975),
component = "all",
simplify = TRUE,
expand = TRUE,
...
)
Arguments
object |
a fitted brma object |
bias_adjusted |
whether to adjust for publication bias. Defaults to
|
probs |
quantiles of the posterior distribution to be displayed.
Defaults to |
component |
random-effect component to return. Defaults to
|
simplify |
whether |
expand |
whether to repeat random-effect contributions for every fitted
observation. Defaults to |
... |
additional arguments forwarded to |
Details
Random effects are computed as the difference between the true effects (BLUPs) and the fixed-effect predictions:
u_i = \hat{\theta}_i - \hat{\mu}_i
For standard (2-level) models, returns a single brma_samples
object with the estimate-level random effects.
For multilevel (3-level) models, returns a list with two
brma_samples matrices:
clusterCluster-level random effects (
\gamma_j \cdot \tau_{between}), representing between-cluster deviations from the fixed effects.estimateEstimate-level random effects (
\theta_i - \mu_i - \gamma_j \cdot \tau_{between}), representing within-cluster deviations from the cluster means.
For brma.mv() random-formula models, decomposes the Gaussian
conditional means by random-effect block. The result is invariant to whether
each block was sampled or marginalized during fitting. If there is only one
block and simplify = TRUE, returns a single brma_samples object.
Multiple blocks are returned in one flat list under their canonical fitted
block names; no additional location layer or component-name prefix is added.
Unique-level output is available when a block's contribution is constant
within each grouping level or observed grouping-level and indicator-
coefficient combination. Other random slopes generally require
expand = TRUE. When the random-effect standard deviation of a block
varies across the rows of one returned cell (a grouping level, or a grouping
level and indicator coefficient) through a scale formula
(also for the cluster component of a clustered model with a scale
formula, whether normal, GLMM, or with a weight function), the unique-level
output is refused with an error of class
RoBMA_ranef_expand_required (also of class
RoBMA_unsupported_request); use expand = TRUE. Only the
components that are returned are judged: component = "estimate" of a
clustered model and a block name whose own scale does not vary are returned,
whereas "all" and "total" include every block. Summed
component = "total" output across multiple blocks also requires
expand = TRUE because different blocks need not share grouping levels.
Value
A brma_samples object for a single selected/simplified
component, or a named list of brma_samples objects for decomposed
component = "all" output. Use summary() on a single component
(as.data.frame() of it returns its draws), or as.data.frame()
on the list, to obtain the displayed summary table in long form, or
as.data.frame(format = "list") to retain separate component tables.
See Also
blup.brma(), predict.brma(), pooled_effect()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
ranef(fit)
}
## End(Not run)
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
- BayesTools
- bridgesampling
- loo
Regression Plot (Bubble Plot) for brma Object
Description
regplot.brma creates a regression plot (also known as
bubble plot) for a fitted brma object with location or scale moderators. The
plot displays observed effect sizes against a moderator variable, with point
sizes proportional to study precision.
Usage
## S3 method for class 'brma'
regplot(
x,
mod = NULL,
pred = TRUE,
ci = TRUE,
pi = FALSE,
si = FALSE,
level = 95,
at = NULL,
digits = 2,
transf = NULL,
atransf = NULL,
targs = NULL,
refline = NULL,
psize = NULL,
plim = c(0.5, 3),
by = NULL,
legend = TRUE,
xlab = NULL,
ylab = NULL,
xlim = NULL,
ylim = NULL,
sampling_bias = TRUE,
sei = NULL,
max_samples = 10000,
plot_type = "base",
as_data = FALSE,
...
)
Arguments
x |
a fitted brma object with location or scale moderators |
mod |
index or name of the moderator variable to plot on the x-axis. If not specified and only one moderator is present, that moderator is used. If multiple moderators are present, this argument is required. |
pred |
logical; whether to show the prediction line. Defaults to |
ci |
logical; whether to show credible interval bands. Defaults to |
pi |
logical; whether to show prediction interval bands. Defaults to |
si |
logical; whether to show sampling interval bands. Defaults to |
level |
numeric; credible/prediction interval level in percent, from
|
at |
numeric vector; for continuous moderators, values at which to evaluate the prediction. If not specified, uses a sequence across the observed range. Continuous evaluation values are sorted with all associated predictions and intervals; duplicate evaluations are retained. |
digits |
integer; number of decimal places for labels. Defaults to |
transf |
function; transformation to apply to the y-axis (effect sizes).
Defaults to |
atransf |
reserved for axis-label transformations. Currently not
implemented and must be |
targs |
reserved for additional transformation arguments. Currently not
implemented and must be |
refline |
numeric; position of horizontal reference line.
Defaults to |
psize |
numeric vector or |
plim |
numeric vector of length 2; range for point sizes.
Defaults to |
by |
character; name of a moderator variable to use for separate
lines/colors. Defaults to |
legend |
logical; whether to show legend when |
xlab |
character; x-axis label. Defaults to the moderator name. |
ylab |
character; y-axis label. Defaults to "Observed Effect Size". |
xlim |
numeric vector of length 2; x-axis limits. Defaults to data range. |
ylim |
numeric vector of length 2; y-axis limits. Defaults to data range. |
sampling_bias |
whether publication bias should be incorporated into
plotted predictions and sampling intervals. Defaults to |
sei |
single positive numeric value used as the reference standard
error for sampling-bias and sampling-interval calculations. Defaults to the
median observed standard error. When |
max_samples |
maximum number of posterior samples used for prediction
summaries and interval bands. Defaults to |
plot_type |
character; whether to use base R graphics ( |
as_data |
logical; if |
... |
additional graphical arguments:
|
Details
The regression plot (bubble plot) is a standard visualization for meta-regression results. It displays:
Observed effect sizes (y-axis) against moderator values (x-axis)
Point sizes proportional to study precision (inverse variance)
Prediction line showing the estimated regression relationship
Confidence bands showing uncertainty in the mean prediction
Optional marginal prediction bands showing the expected range of new true effects
Optional sampling interval bands showing expected range of observed outcomes
For continuous moderators, predictions are computed across the observed
range of the moderator. For categorical moderators (factors), predictions
are computed at each factor level with optional jittering of points.
The other predictors are held at a reference design: continuous predictors
of the location and scale formulas at their means and factors at their
reference levels, predictors of random slopes in the same way (a random slope
whose predictor is held at zero, such as a centered predictor at its mean,
adds no variance to the prediction and sampling bands), and grouping
variables at new row-unique levels. The line and bands describe the regression at
this reference design, not an average over the observed predictor values,
and the prediction and sampling bands are pointwise rather than a joint band
for one random regression curve. For PET/PEESE models with
sampling_bias = TRUE, the line and its credible band include the
expected bias at the reference standard error (sei);
sampling_bias = FALSE shows the bias-adjusted line.
A moderator that appears only in the scale formula produces a constant mean
prediction while prediction and sampling intervals reflect its effect on
heterogeneity.
The credible interval band of a continuous moderator (ci = TRUE) is
formed by pointwise Harrell-Davis quantiles (at the probabilities implied by
level) of the posterior draws of the mean prediction at each grid
value; they are computed by BayesTools::harrell_davis_quantile() on the
model scale, before transf is applied. The Harrell-Davis quantiles
estimate the same quantiles as the empirical quantiles of the draws but
smooth the kinks that the empirical quantiles show along the moderator. The
bands remain pointwise, and, because every draw contributes, they can
differ visibly from the empirical quantiles when few draws are used
(max_samples below a few hundred). Near the edge of a point mass in the
draws (e.g., draws of models that fix the plotted quantity in a
model-averaged posterior) the band blends the point mass and the remaining
draws, and extreme probabilities (e.g., level = 99.9) are not
estimated more accurately than by the empirical quantiles; see
BayesTools::harrell_davis_quantile() for these caveats. The credible
intervals of categorical moderators use the empirical quantiles of the draws
of each level. Prediction and sampling intervals are quantiles of a
different distribution, the posterior predictive mixture over the draws, and
are computed by a different estimator (mixture quantiles, not Harrell-Davis
quantiles of the draws).
Prediction intervals marginalize newly realized random effects. Sampling
intervals use the corresponding marginal response distribution by also
adding representative sampling error; evaluating a fitted moderator value
does not condition these bands on its fitted latent effect.
For marginalized known-R random-effect blocks, pi and si
are unavailable because the group-covariance multipliers belong to the fitted
layout and R_new is unsupported. Use pi = FALSE, si = FALSE
for the mean and credible-interval plot.
For binomial and Poisson GLMMs, prediction intervals retain this latent-effect
interpretation, but sampling intervals are only descriptive normal
approximations on the derived effect-size scale. They are not intervals from
the fitted discrete likelihood and do not use the prior-nuisance marginal
GLMM response target from predict().
The by argument allows displaying separate regression lines for
different levels of a second moderator, useful for visualizing interactions.
For brma.mv() known-V models, prediction and sampling bands are
pointwise descriptive bands. They summarize row-wise marginal random-effect
variation and, for sampling intervals, a representative sampling standard
error. They are not full joint predictive regions for correlated
known-V outcomes.
Value
regplot.brma returns NULL invisibly if
plot_type = "base" or a ggplot object if plot_type = "ggplot".
If as_data = TRUE, returns a list with plot data components.
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(
yi = yi,
vi = vi,
mods = ~ ablat + year,
data = dat,
measure = "RR"
)
regplot(fit, mod = "ablat")
regplot(fit, mod = "year", pi = TRUE, si = TRUE)
regplot(fit, mod = "ablat", plot_type = "ggplot")
fit_cat <- brma(yi = yi, vi = vi, mods = ~ alloc, data = dat, measure = "RR")
regplot(fit_cat)
}
## End(Not run)
Remove a fitted model's selection cache
Description
Removes retained selection-normalizer cache entries from a fitted object without changing its draws, inference, or ability to obtain more draws.
Usage
remove_selection_cache(object)
Arguments
object |
a fitted |
Details
Set RoBMA.options(selection.cache_retain = TRUE) before fitting
or extending to retain exact and coarse cache entries. The default is
FALSE. This option is checked for each RoBMA fit or update() call. Existing
retained entries are used during extension even when retention is turned off;
in that case the returned fit does not retain a new cache.
Retained entries are ordinary serialized data and survive saveRDS().
They are restored only with matching package code, native builds, R and JAGS.
Incompatible or damaged cache data are discarded with a warning; extension
proceeds with ordinary likelihood evaluation. Cache contents never replace
the model, numerical integration controls, or JAGS random-number state.
Reconstructed JAGS models can still require adaptation before collecting new
samples; retaining the normalizer cache does not retain sampler tuning.
Each worker saves its own entries. Extension with the same worker count restores the corresponding worker cache. With a different worker count, previous worker caches are assigned round-robin without duplication, and entries that do not fit the destination's share of the memory budget are dropped. Increasing the worker count can leave some workers with an empty cache initially. Cache reuse can improve speed but is not guaranteed.
Successful capture releases the native cache. A retained object's compact cache payload is bounded by the fitted total native budget, apart from small R metadata overhead. The byte budget is not a limit on total R memory: capture, serialization and extension can temporarily hold both a snapshot and native storage, and other copies or saved fits can retain their own snapshots. Save or load operations can therefore require substantial memory.
Assign the result back to the object to release its reference to the retained
data. Memory remains in use if another object references the same snapshot.
This helper does not clear the current process's independent native cache;
use selection_cache_info(clear = TRUE) for that. Future retention is
controlled by selection.cache_retain.
Value
The fitted object with its retained selection cache removed.
Examples
## Not run:
RoBMA.options(selection.cache_retain = TRUE)
fit <- bselmodel.mv(yi, V = V, random = ~ 1 | study / esid, data = dat)
saveRDS(fit, "fit.rds")
fit <- update(readRDS("fit.rds"), sample_extend = 1000)
fit <- remove_selection_cache(fit)
RoBMA.options(selection.cache_retain = FALSE)
## End(Not run)
Residuals for brma Objects
Description
Computes residuals (observed minus fitted values) from a fitted brma object, with options for standardization.
Usage
## S3 method for class 'brma'
residuals(
object,
type = "outcome",
unit = "estimate",
conditioning_depth = "marginal",
bias_adjusted = FALSE,
max_samples = Inf,
...
)
Arguments
object |
a fitted brma object |
type |
the type of residuals to compute. Options are:
|
unit |
output unit. Only |
conditioning_depth |
conditioning depth for non-LOO residuals. |
bias_adjusted |
whether residuals should be computed from bias-adjusted
fitted values. Defaults to |
max_samples |
maximum posterior draws used for known- |
... |
additional arguments. |
Details
Raw residuals (type = "outcome") are computed as:
e_i = y_i - \hat{\mu}_i
where y_i is the observed effect size and \hat{\mu}_i is the
fitted value (prediction from the fixed effects).
Pearson residuals (type = "pearson") divide raw residuals by the
marginal standard error:
r_i^{Pearson} = \frac{e_i}{\sqrt{v_i + \tau^2}}
where v_i is the sampling variance and \tau^2 is the
relevant heterogeneity component. Only available for normal outcome models
without selection (weightfunction) bias adjustment.
Standardized residuals (type = "rstandard") use the hat matrix to
compute residual standard errors that account for the uncertainty in
estimated coefficients:
z_i = \frac{e_i}{\sqrt{[(I-H)M(I-H)']_{ii}}}
where H is the hat matrix and M is the marginal variance-covariance
matrix. Without additional likelihood weights, the GLS projection satisfies
HM = MH' = HMH', so the
denominator equals
M_{ii} - [X(X'M^{-1}X)^{-1}X']_{ii}, which is strictly smaller than the
Pearson denominator \sqrt{M_{ii}}. This holds with no moderators too,
where fitting the pooled effect alone removes 1/(1'M^{-1}1) from every
residual variance, so standardized and Pearson residuals do not coincide.
Only available for normal outcome models without selection (weightfunction)
bias adjustment.
Likelihood weights affect fitting, the fitted projection, and PSIS
deletion weights; they do not divide the observation variance used for
diagnostic scaling. Pearson residuals and the predictive CDF/moments in
rstudent() use the original outcome law. Internally standardized
residuals combine the fitted weighted projection H with that law's
covariance M, as in metafor diagnostics with custom fitting weights.
RoBMA retains its Bayesian posterior averaging and LOO-PIT transformation;
these are not identical to frequentist deleted-residual z-statistics.
Each retained row produces one residual, without multiplying or repeating it
by its observation weight. Estimate-unit LOO removes the row's entire
weighted likelihood contribution, for integer and non-integer weights alike.
LOO-PIT residuals (type = "LOO-PIT") are the Bayesian equivalent of
studentized deleted residuals (Vehtari et al. 2017). They
are computed via leave-one-out probability integral transformation:
r_i = \Phi^{-1}(u_i)
where u_i = \sum_s w_{is} F(y_i | \theta^{(s)}) is the LOO-weighted CDF
value, w_{is} are the normalized PSIS weights, and F is the
cumulative distribution function of the estimate-unit outcome distribution
under the leave-one-out fit. With likelihood weights, PSIS removes the
weighted likelihood contribution while this CDF remains unpowered.
For weighted Gaussian cluster models, the cluster effect is integrated given
the retained weighted rows. These retained moments are paired with the
integrated powered-likelihood PSIS ratios; full-data sampled cluster effects
are not reused. Numerically unresolved retained moments raise
RoBMA_weighted_gaussian_unavailable, a
RoBMA_numerical_unavailable condition.
Lower and upper probabilities are accumulated
separately on the log scale, and the smaller tail is passed directly to the
normal quantile function. Therefore extreme residuals are not truncated by
probability clipping. Under a correctly specified model, LOO-PIT
residuals should follow a standard normal distribution. Unlike traditional
standardized residuals, LOO-PIT residuals properly account for estimation
uncertainty and leverage without requiring a hat matrix. This is the
recommended method for standardized residuals in Bayesian meta-analysis.
For meta-regression models, fitted values incorporate moderator effects. For models without moderators, all fitted values equal the pooled effect.
For binomial and Poisson GLMMs the fitted predictive distributions are
discrete, so the LOO-PIT residuals are a descriptive normal approximation on
the effect-size scale: F is the normal distribution of the
continuity-corrected log odds ratio or log incidence rate ratio with its
approximate sampling standard error, as metafor computes residuals of
GLMMs. They are not probability integral transforms of the fitted count
likelihood, and the functions say so in a message (plots label the
approximation).
For correlated known-V brma.mv() models, LOO-PIT residuals use
the same conditional estimate-unit target as LOO,
p(y_i \mid y_{-i}, \theta). Random-formula brma.mv() models
support marginal Pearson and internally standardized residuals through the
marginal covariance V + ZGZ' and estimate-depth residuals through the
fitted existing-level random-effect target.
Selection models retain their declared context and original publication
event during deletion. Retained product weights cancel; best selection also
retains the best p-value among the observed outcomes in that event.
Pearson and hat-matrix standardized residuals remain unavailable for
selection models; use LOO-PIT residuals for a likelihood-aware standardized
diagnostic.
The residuals are computed separately for each posterior sample, naturally propagating uncertainty in model parameters to the residuals.
Value
A numeric vector of residual means, one per estimate.
References
Vehtari A, Gelman A, Gabry J (2017). “Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC.” Statistics and computing, 27(5), 1413–1432. doi:10.1007/s11222-016-9696-4.
See Also
predict.brma(), blup.brma(), pooled_effect(), rstandard.brma(), rstudent.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
# raw residuals (default)
residuals(fit)
# Pearson and internally standardized residuals
residuals(fit, type = "pearson")
residuals(fit, type = "rstandard")
# LOO-PIT residuals require stored LOO
fit <- add_loo(fit)
residuals(fit, type = "LOO-PIT")
# residuals from bias-adjusted predictions
residuals(fit, bias_adjusted = TRUE)
# check Pareto k diagnostics
plot(loo(fit))
}
## End(Not run)
Internally Standardized Residuals for brma Objects
Description
Computes internally standardized residuals from a fitted brma
object using the hat matrix or the corresponding known-V GLS/BLUP
projection. Returns a data frame with raw residuals, standard errors, and
standardized residuals (z-values). Available for normal outcome models only.
Usage
## S3 method for class 'brma'
rstandard(
model,
unit = "estimate",
conditioning_depth = "marginal",
max_samples = Inf,
...
)
Arguments
model |
a fitted brma object. |
unit |
output unit. Only |
conditioning_depth |
conditioning depth. Options are:
|
max_samples |
maximum posterior draws used for known- |
... |
additional arguments (currently ignored) |
Details
This function returns a data frame with three columns matching the output
of metafor::rstandard:
-
resid: Projection residuals: marginal depth uses(I - H)y; cluster and estimate depths retain their corresponding random-effect target. Known-Vestimate depth uses the sampling residual projection. Residuals and SDs come from the same projection. These are not the posterior-mean residuals returned byresiduals(type = "outcome"), which subtract the posterior mean of the fitted values and therefore carry the prior's shrinkage; the two agree as the effect prior becomes diffuse. -
se: Standard errors of the residuals -
z: Posterior mean of draw-wise standardized residuals
Internally standardized residuals are computed draw by draw by dividing the
observed residual by its corresponding residual standard error from the hat
matrix. The returned z column is the posterior mean of those draw-wise
ratios, so it is not generally equal to the displayed resid / se
summaries. For correlated known-V models, marginal residuals use the
GLS residual covariance and estimate-depth residuals use the BLUP-style
sampling residual projection. For a correctly specified model, these
residuals should approximately follow a standard normal distribution.
A design-exactly fitted row is set to zero only when its covariance
multiplier has no other partners; fully saturated designs remain exactly
zero under correlated covariance as well. Such a row has residual and
standard error zero and an undefined standardized residual, so its z
is NA (also when it is exactly fitted in only some posterior draws);
qqnorm() omits these rows with a message.
For ensembles whose members differ in their PET and PEESE terms, each draw
uses the design of its member, as described in hatvalues.brma.
This function is only available for normal outcome models without selection
(weightfunction) bias adjustment. Selection models can use
rstudent.brma, which uses LOO-PIT. Internally standardized
residuals are unavailable for binomial and Poisson GLMMs because no
count-likelihood standardization has been implemented. Use
rstudent() (the LOO-PIT residuals) for GLMMs.
For known-V models, the standardized residuals require applying the
inverse of the marginal covariance. A covariance that is too ill-conditioned
for that (a reciprocal condition number of about 2e-10 or less in any
posterior draw used) is unavailable: the call stops with an error of class
RoBMA_known_v_precision_unavailable, whose parent class is
RoBMA_numerical_unavailable, instead of returning a rounded number.
The condition carries the draw positions (rows) and their
reciprocal_condition.
These positions refer to the current request after deterministic thinning,
including estimate-depth requests.
Value
A data frame with columns:
-
resid: Posterior mean projection residuals at the requested depth -
se: Standard errors of the residuals -
z: Standardized residuals
See Also
rstudent.brma(), residuals.brma(), blup.brma(), predict.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
# marginal internally standardized residuals (default)
rstandard(fit)
# estimate-level (BLUP-based) residuals
rstandard(fit, conditioning_depth = "estimate")
}
## End(Not run)
Externally Standardized (Studentized) Residuals for brma Objects
Description
Computes externally standardized residuals (also called studentized residuals or standardized deleted residuals) from a fitted brma object using LOO-PIT (Leave-One-Out Probability Integral Transform). Returns a data frame with raw residuals, standard errors, and standardized residuals (z-values).
Usage
## S3 method for class 'brma'
rstudent(model, unit = "estimate", conditioning_depth = "marginal", ...)
Arguments
model |
a fitted brma object. |
unit |
output unit. Only |
conditioning_depth |
unused for LOO-PIT residuals. LOO-PIT residuals always use the estimate-unit LOO target. |
... |
additional arguments (currently ignored) |
Details
This function returns a data frame with three columns matching the output
of metafor::rstudent:
-
resid: LOO predictive residuals (observed - fitted values) -
se: LOO predictive standard errors when available -
z: Externally standardized residuals (LOO-PIT transformed)
LOO-PIT residuals are the Bayesian equivalent of studentized deleted residuals. They are computed via leave-one-out probability integral transformation using Pareto smoothed importance sampling. For each observation, the LOO-weighted CDF is computed and transformed to a standard normal quantile.
Under a correctly specified model, LOO-PIT residuals should follow a standard normal distribution. Large absolute values may indicate outliers or model misspecification.
The z column is the primary standardized diagnostic. The resid
and se columns are raw-scale companions computed from LOO predictive
moments using the normalized PSIS weights. For selection models, these moments
are computed from the fitted selected-normal predictive distribution.
Unlike rstandard.brma (which uses the hat matrix), LOO-PIT
residuals properly account for estimation uncertainty and leverage without
requiring explicit hat matrix computation. For binomial and Poisson GLMMs the
residuals are a descriptive normal approximation on the effect-size scale
(see residuals.brma), not a PIT of the fitted count likelihood,
and a message says so.
For correlated known-V brma.mv() models, the PIT and companion
residual moments are computed from the Schur-complement conditional
predictive distribution used by estimate-unit LOO.
Value
A data frame with columns:
-
resid: Raw residuals -
se: Standard errors of the residuals -
z: Externally standardized residuals (LOO-PIT)
See Also
rstandard.brma(), residuals.brma(), loo.brma(), blup.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
fit <- add_loo(fit)
# externally standardized residuals
rstudent(fit)
# check Pareto k values
plot(loo(fit))
}
## End(Not run)
Inspect or clear the native selection cache
Description
Reports the bounded native selection-normalizer cache in the current R process. Exact caching reuses identical numerical inputs and does not change the likelihood or its integration diagnostics. Post-fit requests using bounded CDF interpolation bypass these caches, including when they fall back to the ordinary primitive. Fitting retains its ordinary-primitive cache.
Usage
selection_cache_info(clear = FALSE, component = c("all", "exact", "coarse"))
Arguments
clear |
clear the requested entries and reset their counters before
reporting them. Clearing |
component |
report the |
Details
The default selection.cache_max_bytes = "auto" chooses the
smaller of 4 GiB and one quarter of currently available system RAM. Available
RAM is reported by ps::ps_system_memory(), excluding swap. A numeric
setting supplies an explicit total byte budget; 0 disables storage.
If the available-memory query fails, a warning is issued and caching stays
disabled until a budget can be resolved or supplied explicitly.
Loading the package does not query available memory. The first selection
computation or cache inspection initializes the current process's cache, including computations
on a saved fit. Explicit option changes and fitting setup also initialize it.
Exact and coarse entries share one byte budget for directly allocated key,
control, list-node and index blocks, with global least-recently-used eviction.
Storage is allocated lazily. The ordinary sampler does not use coarse entries.
The budget is resolved once before fitting and divided equally among chains. Shares are pooled for chains assigned to the same process: ten parallel workers receive one tenth each, while ten sequential chains share the total. Integer-byte rounding can leave a few bytes unused. The coordinator releases its cache while workers run and restores its local budget when they stop. Separate simultaneous fits are separate budgets; this is not a machine-wide memory manager. Stored fit extensions retain the resolved budget and sampler settings, redistributing the budget for their current worker topology.
This function reports only the current process, not separate workers or saved
fitted-object caches. By default entries live in the native process. Set
RoBMA.options(selection.cache_retain = TRUE) to retain them with the
fit; see remove_selection_cache. Changing
the budget or clearing all entries releases the shared storage. Clearing one
component releases its keys, nodes and controls; shared index buckets can remain
allocated. Switching sampler options does not clear existing entries or replace
already compiled samplers.
The exact cache accelerates successful deterministic covariance-envelope normalizers for multivariate step selection. Unsupported numerical routes continue through their ordinary evaluator. The coarse cache can also store its prescribed unit-normalizer fallback. If cache storage cannot be allocated, the same exact or surrogate evaluator runs without storage; memory capacity never determines the returned normalizer or its numerical diagnostics.
Value
A data frame with the cache component, byte counts, entry count, and
lookup, eviction and allocation counters. The "total" row reports the
shared capacity and directly allocated blocks, including retained controls and
index buckets; component byte counts are NA because storage is shared.
Allocator metadata, the surrounding R process and JAGS model are excluded;
this is not a process-RSS limit. Eviction releases entry blocks, while controls
and index buckets can remain allocated. Oversize lookup keys increment misses
without incrementing allocation failures. Failed insertion, capacity or
allocation attempts can increment allocation failures; these counts do not
necessarily indicate exhaustion of system memory.
Selection Model
Description
Declare the contextual sources retained by a selection model, how estimate weights combine, and a publication-group column for best-p-value selection when needed.
Usage
selection_model(
estimate_random_effects = "integrate",
other_random_effects = "condition",
known_sampling_variance = "integrate",
weight_rule = "product",
group = NULL
)
Arguments
estimate_random_effects |
Either |
other_random_effects |
Either |
known_sampling_variance |
Either |
weight_rule |
Either |
group |
Optional unresolved data-column name, supplied as a bare name,
a backtick-quoted name, or one character string. Active only for
|
Details
This is RoBMA's re-export of BayesTools::selection_model().
The specification is stored in prior_weightfunction(model = ...).
Constructor selection = selection_model(...) settings apply only
to generated default priors; explicit priors retain their own specification.
A group name is captured without evaluating data; RoBMA binds it only for
weight_rule = "best". When group = NULL, best-rule groups come
from a supported constructor's cluster input or, for independent models
without a random structure, one group per estimate. Other best-rule models
require an explicit group column. Conditioned sources remain unknown and
estimated.
Integrating estimate variation is the default; conditioning on it defines
a different selection model. The specialized clustered interface retains
its total heterogeneity, allocation and within-/between-cluster I2 summaries.
With positive sampling standard errors, the sampling law can be written as
e = Sz, with
z \sim N(0,R) and V = SRS, where S contains sampling
standard errors and R is their correlation matrix. Conditioning
retains all of e; no residual sampling error is integrated separately.
Covariance factorizations affect computation, not the selection model.
Selection thresholds continue to use the original sampling standard errors.
When all outcome-generating sources are conditioned upon and weights are
positive almost surely, selection weights cancel and the observed law is
the ordinary Gaussian model. The likelihood then contains no information
about the selection weights. A retained context with zero acceptance
probability cannot complete the selection process. Integrating all sources
instead gives population-level selection among completed studies.
These choices are independent of prediction's conditioning_depth.
Non-unit observation weights require
known_sampling_variance = "integrate"; unit weights are equivalent
to omitting weights. Other observation-weight restrictions still apply.
weight_rule = "best" uses the weight of the smallest p-value's bin,
rather than the largest weight. weight_rule = "product" multiplies
all estimate weights. Its joint normalizer retains the dependencies in the
integrated covariance, regardless of grouping. In ensembles, only best-rule
branches require matching publication partitions; product-only ensembles
accept group = NULL.
See bselmodel.mv() for the supported conditioning cells, source and group
requirements, and covariance boundaries.
Value
A selection_model object containing fixed mode choices and a
deferred column name or NULL. The group is used only by the best rule.
See Also
prior_weightfunction, bselmodel.mv(), RoBMA.mv()
Examples
prior_weightfunction(
steps = .05,
model = selection_model(known_sampling_variance = "condition")
)
prior_weightfunction(
steps = .05,
model = selection_model(weight_rule = "best", group = paper_id)
)
Inspect corrected selection-sampler counters
Description
Counts completed coarse slice proposals and their full-target acceptance decisions in the current R process.
Usage
selection_sampler_info(clear = FALSE)
Arguments
clear |
reset counters before reporting them. |
Details
Enable the alternative for future fits with
RoBMA.options(selection.sampler = "coarse_corrected").
Every proposal is corrected against the full original likelihood and prior.
Only the selection normalizer used to construct proposals is coarsened.
A reversible slice transition for that surrogate is followed by a
Metropolis correction using both original and surrogate densities at the
current and proposed states. The original likelihood keeps its existing
numerical integration controls and diagnostics; the correction does not
replace those numerical integrals by symbolic exact values.
Dense multivariate step blocks. The surrogate rounds means and the
logarithms of positive weights to fixed grids. Each covariance diagonal is
rounded upward on a grid whose origin is that row's squared original
sampling SE; off-diagonal covariances, original SEs, selection cutoffs, and
zero weights are retained. These are proposal grids, not changes to fitted
variance components or the input covariance. The Gaussian numerator and
observed weights use the actual parameters. At most the first
selection.coarse_max_rules rules of the fitted quadrature schedule
are tried, with its existing integration criterion. If a valid anchor cannot
be constructed or its covariance-envelope calculation is unsupported or
unsuccessful, its prescribed normalizer is one; the proposal stage does not
fall back to QMC. This fallback is independent of cache history and memory
capacity and remains subject to the full-target correction. It does not
replace full-target integration failures.
Rank-one cluster and factor step blocks. The surrogate is the exact
numerator (Gaussian log density and observed log weights at the actual
parameters) minus the log normalizer of one rule of the block's own
Gauss-Hermite schedule: rule number selection.coarse_max_rules, or the
last rule of a shorter schedule, evaluated at the actual parameters. No grid
rounding, change test, certificate, refinement, sparse grid, QMC or cache
enters, so the surrogate is a deterministic function of the sampled state;
the correction evaluates the exact block, which keeps its ordinary numerical
controls and diagnostics. Where that rule is unavailable at an update (a
best-weight rule in the current state, or a non-finite normalizer) the
surrogate is the exact density of the block. A block takes part unless its
fixed controls rule it out: a weight rule fixed at a best-weight rule, a
kernel mode fixed at the normal kernel, or, for a factor block, a rule beyond
the node budget at the declared rank (rank two to six at the default
setting). In model-averaged fits the weight rule and the kernel mode are
nodes of the bias indicator, so their blocks take part, with the exact
density in the states of the indicator that have a best-weight rule. A model
average whose selection branches all use the best-weight rule takes part
without any state that can gain: its surrogate is the exact density everywhere
and every update pays two extra exact evaluations, so run such fits with the
default sampler. Blocks fixed at a best-weight rule, blocks of higher rank and
blocks with a fixed normal kernel keep the ordinary sampler.
A scalar update is eligible when at least one stochastic child of the updated node is a dense multivariate block or a coarse-capable cluster or factor block; its other children enter the surrogate through their exact densities. Discrete, vector-valued and unrelated updates, and updates whose selection children are all without a coarse rule, retain ordinary JAGS samplers, so the option can be set without effect: check that the counters grow. Whatever the surrogate, the corrected chain targets the exact full conditional; a coarser rule changes the acceptance rate and the cost, not the posterior.
Already compiled samplers retain their grid and coarse rule-budget settings. Coarse settings can affect sampling efficiency even when correction acceptance is high. Compare effective samples per second for parameters of interest, not only iteration times or this acceptance rate. Counters combine all corrected samplers in this process, including warmup; clear them between phases for a sampling-only comparison. They do not report separate parallel workers. Inspect them between sampling calls.
Value
A data frame with proposal, acceptance and correction-rejection
counts, and an acceptance rate (NA before any proposals).
Diagnose Selection Conditioning Sensitivity
Description
Describes how integrating the contexts retained by a fitted selection model would reweight their pre-selection Gaussian distribution. This compares reporting models; it is not a numerical approximation error bound.
Usage
selection_sensitivity_diagnostics(
object,
max_posterior_samples = 256L,
latent_samples = 512L,
seed = 1L,
integration_control = NULL
)
add_selection_sensitivity_diagnostics(object, ...)
Arguments
object |
A fitted normal-outcome model with a bound selection model. |
max_posterior_samples |
Maximum number of posterior draws to evaluate.
A positive integer of at least |
latent_samples |
Number of fresh pre-selection retained-context draws
per posterior draw. Must be one finite integer of at least |
seed |
Integer seed for the diagnostic simulation. The calling R session's random-number state is restored before returning. |
integration_control |
Optional settings from
|
... |
Simulation arguments passed to
|
Details
At each posterior draw the fitted model defines a conditional Gaussian response law, retained contexts, and any best-rule publication groups. The diagnostic evaluates each Gaussian selection unit's normalizer at fresh retained contexts, preserving the fitted product or best weight rule and any best-rule publication groups. Product-only models require no grouping. Within a connected source unit, their product gives the relative reweighting when the retained contexts are integrated before selection normalization. Sampling-conditioned comparisons use the fitted candidate factors, including singular declared support. Integration diagnostics report maxima over the constituent event evaluations, rather than an error bound for their product.
ess_fraction estimates mean(W)^2 / mean(W^2);
this is a retained-context reweighting ESS fraction within each posterior
parameter state, not the posterior sample ESS.
total_variation estimates the distance between the pre-selection context
law and its normalized W-reweighted law. The fitted and reference
conditioning specifications, publication identities, and source roles are
retained in the target attribute. With no retained context this comparison
is inapplicable and its reweighting is identically constant.
The fitted weight rule is held fixed. These summaries do not compare arbitrary weight rules, identify the correct reporting mechanism, or reveal parameter regions absent from the fitted posterior.
Simulation budgets control diagnostic Monte Carlo precision separately from
the fitted Gaussian event integration controls. The largest unit-level
posterior-median total variation distance is silent up to 0.05, produces
a message above 0.05 and below 0.10, and a warning from 0.10.
These notifications describe sensitivity rather than statistical adequacy.
This optional comparison is computed only when requested; fitting does not
compute it. Calls without simulation arguments reuse an explicitly stored
result, and explicit settings reuse it only when they match. Use
add_selection_sensitivity_diagnostics() to compute and store a result.
Chain extension silently refreshes only stored diagnostics using their stored
simulation settings; label-only updates retain them. Failed refreshes remain
stored as unavailable without discarding the fitted posterior. Call
selection_sensitivity_diagnostics() to inspect the comparison or its error.
Sensitivity notifications are emitted only by these explicit helper calls,
not by fitting, extension, or ordinary model printing.
The substantial-sensitivity warning has class
RoBMA_selection_sensitivity_warning, retaining simpleWarning, warning,
and condition. Its fields are maximum_total_variation, threshold (0.10),
and comparison ("retained_context_reweighting"). Own nonfinite normalizer
refusals have class RoBMA_selection_sensitivity_normalizer_unavailable and
fields reason, posterior_draw (the evaluated posterior-row index),
latent_draw, event, and the observed log_mass values. Unsupported retained
covariance has class RoBMA_selection_sensitivity_covariance_unavailable and
reason = "retained_covariance_unavailable". Both refusals inherit from
RoBMA_selection_sensitivity_error, simpleError, error, and condition.
Downstream integration failures retain their original conditions.
Value
A data frame with one row per connected source unit, identified by
block, comma-separated observation rows, and n_estimates. The
ess_fraction, total_variation, and log_weight_iqr summaries each have
_q05, _median, and _q95 columns across all evaluated posterior draws,
including non-selection draws. The ess_fraction_mcse and
total_variation_mcse columns have _median and _max suffixes for
conditional Monte Carlo uncertainty. integration_relative_mcse_max and
integration_relative_quadrature_error_max are maxima over constituent
event evaluations, not an error bound for the multiplied unit weight.
posterior_samples, total_posterior_samples, and latent_samples report
the simulation budgets. The settings attribute records
max_posterior_samples, latent_samples, seed, and integration_control.
The target attribute records the comparison, fitted and reference models,
applicability, source roles, fitted and reference sampling structures,
publication groups, likelihood unit, row blocks, and resolved event
integration settings. The add function returns the fitted object.
See Also
bselmodel.mv(), set_selection_likelihood_control()
Control numerical integration of selection likelihoods
Description
Creates numerical integration settings for the product and best-p-value
selection likelihoods used by bselmodel(), bselmodel.mv(), RoBMA(), and
RoBMA.mv(). Covariance factors use deterministic sequences of
Gauss-Hermite rules. Certified factors of structural rank one through eight
use deterministic interval refinement for rank-one product fallbacks and
randomized quasi-Monte Carlo for other unresolved factor integrals.
General covariance blocks with
product weights first try same-diagonal covariance approximations with a
common Gaussian factor and independent group factors. Monotone weights
permit covariance bounds on the normalizer. Two-sided and other nonmonotone
weights require a covariance-perturbation bound; agreement of auxiliary
normalizers alone is insufficient. The absolute bound uses the total
variation of the step weights. Strictly positive weights also permit a
relative Gaussian covariance bound, including reconstructed diagonal and
factor rounding, which remains useful for tiny normalizers. Their original
full covariance remains authoritative.
The covariance error bound, estimated
quadrature error, and a bound on Gaussian mass outside the quadrature nodes
share one numerical error budget. Interior quadrature error is estimated,
so this is not a rigorous probability interval. Unsupported or unresolved
cases use randomized quasi-Monte Carlo in the dense conditional-normal
representation.
Under product weights, a deterministic rung of the factor or cluster
quadrature ladder is accepted by a shift-amplitude certificate. Shifting the
nodes of one latent axis by a fraction of the node gap and reweighting leaves
the integral unchanged, so the change of the rule under half and quarter gap
shifts of each axis measures its aliasing error. The rung's successive
changes must be within relative_tolerance, the summed shift amplitudes must
not exceed half of it, and twice their sum, together with the exterior
Gaussian mass, must fit within it. A rung must also resolve the selection
edges: the edge width (conditional residual SD divided by the absolute
loading) is at least 0.15 times the node gap. When no rung is accepted,
rank-one clusters, tensors of rank at most two and depth-one forests try the
average of the finest rung over four shifts per axis before sparse grids and
the randomized fallback. That average asks the edges for at least one eighth
of the node gap, with a separate penalty for each axis's row count, and is used only when
relative_tolerance is at least 0.005, the tolerance at which its checks
were calibrated. For product weights with selection transitions, the ladder
and this refinement tier use the smaller of relative_tolerance and 0.005
for their acceptance checks: a loose request must not relax the calibration
of these deterministic rules. After these checks decline, rank-one product
integrals refine bounds over the complete Gaussian line, including both tails.
Exact row groups and nonnegative excess weights give interval extrema; the
returned midpoint must satisfy the requested relative tolerance against both
bounds. Floating arithmetic uses an explicit working-precision allowance,
rather than a universal guarantee for library probability evaluations.
Insufficient work or unresolved arithmetic is rejected without a QMC retry.
Other randomized fallbacks retain the requested tolerance and their empirical
diagnostics. The best-p-value rule and the other deterministic routes
instead require that the node gap across an interior transition not exceed
its conditional residual SD divided by the absolute loading; coupled axes use
conservative central node spacing. Unresolved candidates refine or use the
existing fallback; the numerical settings and likelihood target are
unchanged. These checks are heuristics, not a bound on the total integration
error, including reciprocal normalizers.
Each fit or post-fit request uses a fixed integration design, so repeated
likelihood evaluations are deterministic. One-observation blocks are evaluated
analytically.
Post-fit dense two-bin product normalizers can use a bounded interpolation of the standard-normal CDF. Its deterministic error is included in the same numerical error budget, separately from Monte Carlo standard error. Other weights, arithmetic outside its supported range, or insufficient error budgets retain the ordinary scalar primitive. An unresolved interpolation attempt retries the ordinary covariance-envelope calculation before QMC. Fitting and random generation retain their ordinary scalar primitive.
The numerical defaults are package operating settings, not statistical
estimands or literature-mandated constants. points_per_scramble,
max_points_per_scramble, and scrambles set the fixed computational
design, while
relative_tolerance sets its diagnostic acceptance rule. Increasing a
budget changes only the numerical evaluation of the same likelihood target.
For qCMDE/IWMDE post-fit densities and hypotheses in Gaussian selection
models, pass this object as
density_control$integration_control, for example
density_control = list(integration_control = set_selection_likelihood_control(max_points_per_scramble = 32768)).
The default NULL retains the fitted integration settings. An explicit
control rebuilds a temporary execution plan from the stored covariance
metadata without changing the fitted object or its posterior draws.
In fitting and qCMDE/IWMDE likelihood evaluation, the maximum point budget
controls factor QMC fallback and the rank-one product refinement work ceiling.
For rank-one refinement, max_points_per_scramble and scrambles allow at
most their product (with max_points_per_scramble rounded up to an even
number) times the active exact row-group count times the positive
excess-weight bin count in scalar probability evaluations. This includes
latent interval masses and bound preparation. Active intervals are limited
to the same product and to the existing native node ceiling.
points_per_scramble initializes QMC
routes only. Post-fit full-event and partial-event
calculations, including z-plots and sensitivity diagnostics, also refine
dense QMC evaluations up to that budget. Analytic and deterministic
quadrature rules remain unchanged.
Usage
set_selection_likelihood_control(
points_per_scramble = 512L,
max_points_per_scramble = 8192L,
scrambles = 8L,
relative_tolerance = 0.005,
seed = 1L
)
Arguments
points_per_scramble |
nominal number of integrand evaluations per randomized quasi-Monte Carlo scramble for certified factor fallbacks, and the number of shifted Halton points for general covariance blocks. Factor likelihood-normalizer fallbacks under product weights combine the prior Gaussian with a Gaussian at the tilted mean and covariance of the finest quadrature rung and a copy with 1.5 times its standard deviations, where the quadrature provides them (tensors and depth-one forests with at least three finite rules, exterior mass covered and a positive definite covariance). Otherwise, and for the best-p-value rule, they combine the prior Gaussian with proposals optimized from zero and selection-boundary starting points. Every finite optimized candidate is retained, including candidates that locate the same mode. The total count is divided as evenly as possible across the proposals, and importance weights use the actual allocation. Odd likelihood-normalizer factor budgets use the next even total because the fixed design uses two streams. This count is the initial nested-design budget, not an accuracy guarantee. The integration diagnostics determine whether it is adequate for each evaluated likelihood state. Selected-density projection fallbacks instead retain the prior Gaussian and one proposal optimized from zero. |
max_points_per_scramble |
largest nested-design budget used for a
certified factor fallback, including fitting-time refinement, or a post-fit Gaussian event
calculation, when the initial |
scrambles |
number of independent randomized shifts used to estimate
integration error for certified factors and general covariance
blocks. The stopping multiplier of |
relative_tolerance |
largest accepted successive relative quadrature
change for factor integration, or the largest nested-design relative
change and 2.36 times the relative Monte Carlo standard error for a factor
fallback and for the conditioned-sampling normalizer.
Rank-one product interval refinement instead checks the conservative
relative radius of the actual returned midpoint against both bounds.
General covariance
blocks and Gaussian event integrals use 2.36 times the relative Monte
Carlo standard error alone. Dense covariance-envelope
quadrature additionally requires the
sum of covariance-bound width, twice the successive quadrature change,
the relative exterior-mass bound, and any post-fit CDF interpolation error
to satisfy this tolerance. Factor quadrature also checks exterior Gaussian
mass before accepting rule agreement; an unresolved rule sequence uses the
existing QMC fallback. The returned deterministic candidate also requires
its shift-amplitude certificate under product weights (summed shift
amplitudes within half of this tolerance and twice their sum, with the
exterior mass, within the tolerance; the four-shift average that follows a
rejected ladder is used only for tolerances of at least 0.005) or, on the
other routes, selection-transition resolution; coarser comparison rules
retain their actual values without an added resolution requirement. The
randomized fallback stops when the larger of its relative change and 2.36
times its relative Monte Carlo standard error (the 97.5% quantile of
Student's t distribution with seven degrees of freedom, for eight
scrambles) is within this tolerance, and a result that does not pass that
test is rejected; the reported standard error stays unscaled, and the
criterion does not bound the error of the accepted value. Zplot
projections additionally check density error relative to the peak within
each posterior draw and raw normalizer-mass diagnostics, including their
bounded approximation and omission terms. These diagnostics do not certify
the total integrated error of a compressed displayed curve; see
|
seed |
non-negative integer used only to create fixed quasi-Monte Carlo designs. It does not alter R's random-number state. |
Value
A RoBMA_selection_likelihood_control object.
Summarize brma Object
Description
summary.brma creates summary tables for a
brma object. For RoBMA objects, inclusion summaries are printed before
parameter estimates. Random-effect inclusion rows are included in
Component Inclusion, immediately before Publication Bias when present.
Their labels prefix the corresponding SD quantity with Heterogeneity:, retaining
component names where needed. Data-frame exports use the same layout.
Usage
## S3 method for class 'brma'
summary(
object,
probs = c(0.025, 0.5, 0.975),
include_mcmc_diagnostics = TRUE,
standardized_coefficients = FALSE,
conditional = FALSE,
logBF = FALSE,
BF01 = FALSE,
...
)
## S3 method for class 'summary.brma'
print(x, ...)
## S3 method for class 'brma'
print(x, ...)
Arguments
object |
a fitted brma object |
probs |
quantiles of the posterior samples to be displayed.
Defaults to |
include_mcmc_diagnostics |
whether to include MCMC diagnostics in the output.
Defaults to |
standardized_coefficients |
whether to show standardized formula
coefficients. Defaults to |
conditional |
whether to include conditional estimates for RoBMA
product-space objects. Defaults to |
logBF |
whether to show inclusion Bayes factors on the log scale.
Defaults to |
BF01 |
whether to show inverse inclusion Bayes factors. Defaults to
|
... |
unused additional arguments. Supplied arguments trigger a warning. |
x |
a |
Value
A list of class summary.brma with model name, optional RoBMA
inclusion tables, common estimates, moderator estimates, scale estimates,
publication-bias estimates, and optional conditional estimates.
known_v_backend records the known-sampling-covariance backend.
inclusion_random contains random-effect inclusion tables;
selection_model, selection_sampling, and
selection_sensitivity_diagnostics retain selection-target metadata
and optional sensitivity diagnostics. The printed
form displays the non-empty tables. Objects created with only_data = TRUE
return the resolved data, and objects created with only_priors = TRUE
return a summary.brma object that prints only the model title, as at 4.0.0,
and holds the resolved prior list in its priors element, because neither
carries a posterior.
Intercept-only multivariate location
models label their sole coefficient mu, consistently with ordinary
meta-analysis models. Once location moderators are present, the coefficient
is labeled intercept; an intercept fixed at zero is omitted.
Multivariate models without mods or scale display location and random
estimates together in one Estimates table. With predictors, random estimates
join Common Estimates, location coefficients appear in Meta-Regression
(or Location when scale is present), and scale coefficients appear in
Scale. Without location moderators, mu remains in the common table.
Conditional estimates follow the same layout. Data-frame conversion follows
these displayed sections; the returned list retains its separate raw tables.
Scale tables label the baseline SD as exp(intercept); its estimates are
already exponentiated. Other scale coefficients remain on the log-SD scale.
Multivariate scale rows identify their targeted random-effect heterogeneity
(tau), total heterogeneity (tau_total), or mean-variance allocation scale
(tau_common). The baseline
corresponds to zero non-intercept design columns under the fitted contrasts
and the requested predictor standardization.
The random table reports the quantities aligned with prior specification;
use summary_heterogeneity() for aggregate variances and the complete family
of deterministic allocation transforms.
This reporting rule is the same for brma.mv() and BMA.mv(): component
tau values derived from a variance allocation appear only in
summary_heterogeneity().
Optional selection-conditioning comparisons are inspected explicitly with
selection_sensitivity_diagnostics(). Printing a model or its summary does
not emit sensitivity notifications.
Fitted objects store their default summary, so print() and summary()
without further arguments return it without recomputation; update() and
add_selection_sensitivity_diagnostics() store it again.
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
summary(fit)
}
## End(Not run)
Summarize brma_samples Object
Description
Creates and returns a summary table of posterior samples
using BayesTools::ensemble_estimates_table.
Usage
## S3 method for class 'brma_samples'
summary(object, probs = NULL, ...)
Arguments
object |
a |
probs |
quantiles for credible intervals. If |
... |
additional arguments passed to
|
Value
A BayesTools_table object containing the summary statistics.
Summarize Estimated Marginal Means
Description
Summarizes estimated marginal means stored in a
marginal_means.brma object using
BayesTools::marginal_estimates_table().
Usage
## S3 method for class 'marginal_means.brma'
summary(
object,
type = NULL,
probs = c(0.025, 0.5, 0.975),
logBF = FALSE,
BF01 = FALSE,
bf = NULL,
output_measure = NULL,
transform = NULL,
...
)
Arguments
object |
a |
type |
for RoBMA product-space objects, whether to summarize
model-averaged ( |
probs |
quantiles of the posterior distribution to be displayed.
Defaults to |
logBF |
whether to show inclusion Bayes factors on the log scale.
Defaults to |
BF01 |
whether to show inverse inclusion Bayes factors. Defaults to
|
bf |
whether to show inclusion Bayes factors. Defaults to the setting
stored by |
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
... |
unused additional arguments. Supplied arguments trigger a warning. |
Value
A BayesTools_table of class
summary.marginal_means.brma.
Summarize Zplot Results
Description
Creates summary tables for zplot estimates including EDR, Soric FDR, and the conventional missing-count diagnostic when applicable.
Usage
## S3 method for class 'zplot_brma'
summary(object, probs = c(0.025, 0.975), ...)
Arguments
object |
a zplot_brma object. |
probs |
quantiles of the posterior distribution to display.
Defaults to |
... |
additional arguments (currently unused). |
Details
The summary includes:
- EDR
Expected Discovery Rate - the posterior average probability of significance for a new outcome from the bias-adjusted reference
- Soric FDR
Expected proportion of false discoveries among significant results, computed from EDR following Soric (1989)
- Missing N
The retained reference-bin-normalized inverse-weight diagnostic for independent univariate and conditional-cluster product models. See
as_zplot.brma()for the additional assumptions required by a literal count interpretation. Unavailable for multivariate models, retained estimate-level or sampling-error sources, applicable integrated contexts, or best-rule selection models because relative weights do not identify a missing count
The footer reports the Observed Discovery Rate (ODR) with 95% CI for comparison with the model-estimated EDR.
Value
An object of class "summary.zplot_brma" containing the
estimates table.
See Also
as_zplot.brma(), plot.zplot_brma()
Summary of Heterogeneity
Description
Computes method-specific absolute and relative heterogeneity summaries for a fitted model.
Usage
summary_heterogeneity(object, ...)
Arguments
object |
a fitted model object |
... |
additional arguments passed to methods |
Value
Method-specific return value containing heterogeneity estimates.
See Also
pooled_heterogeneity(), summary.brma()
Summary of Heterogeneity for brma Objects
Description
Computes the absolute heterogeneity (tau, tau^2) and relative measures of heterogeneity (I^2, H^2) for a fitted brma object.
Usage
## S3 method for class 'brma'
summary_heterogeneity(object, probs = c(0.025, 0.975), component = "all", ...)
## S3 method for class 'summary_heterogeneity.brma_list'
print(x, ...)
Arguments
object |
a fitted brma object |
probs |
quantiles of the posterior distribution to be displayed.
Defaults to |
component |
heterogeneity component to return for |
... |
additional arguments (currently ignored) |
x |
a |
Details
For standard (2-level) random-effects models, the function reports:
-
tau: Between-study standard deviation -
tau2: Between-study variance -
I2: Percentage of total variance due to heterogeneity -
H2: Ratio of total to sampling variance
For multilevel (3-level) models with nested effects, the function additionally partitions heterogeneity into estimate-level and cluster-level components:
-
rho: Proportion of heterogeneity variance allocated to clusters -
tau [within]: Estimate-level standard deviation -
tau [between]: Cluster-level standard deviation -
tau2 [within]: Estimate-level variance -
tau2 [between]: Cluster-level variance -
I2 [within]: Percentage of variance due to estimate-level heterogeneity -
I2 [between]: Percentage of variance due to cluster-level heterogeneity
For location-scale models, tau2 aggregates the observation-specific
heterogeneity variances \tau_i^2; the corresponding tau summary
is the square root of this aggregate variance. The relative I^2 and
H^2 measures average the observation-specific indices.
The I^2 and H^2 statistics are computed following the metafor package
implementation, using the "typical" sampling variance formula from
Higgins and Thompson (2002). For multilevel models,
the partitioned I^2 follows the approach described in the metafor documentation.
For RoBMA() ensembles whose members differ in their PET and PEESE
terms, each draw uses the typical sampling variance of its member's design
(see hatvalues.brma).
For brma.mv() models, the method reports tau and tau2
for each selected random-effect component. A genuine variance-additive
aggregate is reported as tau_total and tau2_total; a
mean-variance allocation scale is reported as tau_common and
tau2_common. These RoBMA I/O names map to BayesTools' general
random-effect names without changing the fitted quantities. Formula-random
summaries are present only when a
random formula is declared.
A random-effect quantity that the fitted block cannot represent on the
original predictor scale (for example the intercept SD, variance and
correlations of a block with factor-specific slopes of a standardized
predictor) is NA, with a row note, in the row that shows it. This
table shows the SDs, variances and correlations, so all of them can be
NA here; summary.brma shows the correlations and the
fitted-scale multipliers, so only its correlation rows can be NA.
Public random-effect correlations (rho) are included in their component's
table,
including homogeneous structures such as ar(), cs(), and
car(). A variance-additive total across multiple components has no
single correlation parameter and reports only its total SD and variance.
When a known group covariance R is supplied, tau is the fitted
base multiplier of that covariance kernel. It need not equal every row's
marginal standard deviation when \mathrm{diag}(R) is not one.
Row-specific marginal standard deviations remain available from
predict(type = "terms.scale") and in covariance-based prediction and
diagnostics.
I^2 and H^2 use the original sampling variances and the fitted
location design to define the typical sampling variance. Likelihood weights
affect these summaries through the posterior heterogeneity but do not
replace the sampling variances v_i by v_i / w_i, so rescaling all
weights does not change the reference variance (as in metafor).
Relative I^2 and H^2 summaries are not reported for general
known-V covariance structures, nor for a meta-regression whose location
design leaves no residual degrees of freedom (as many estimable coefficients
as estimates), where the typical sampling variance is undefined. For component = "total", independent
component variances are summed before reporting tau2_total;
tau_total is the square root of this variance draw.
When a random-formula model uses a shared total-SD plus variance-allocation
node, component = "all" also includes an allocation-node table with
the appropriate aggregate SD and variance plus
tau2_prop(<block>) rows. For gated allocations, the aggregate is the
realized model-averaged total and includes the all-off zero branch;
proportions are realized shares conditional on positive total variance.
For nested formulas
such as random = ~ 1 | study / esid, this table is displayed under
the user-facing path "study/esid".
For heterogeneous structured random effects, such as
random = ~ har(time | study), the allocation table reports
the exhaustive semantic allocation family: aggregate SD and variance,
level-specific component SDs and variances, correlations, SD multipliers, and
variance multipliers. For row-shaped scale sources, absolute level SDs and
variances use the observed rows assigned to each level; their aggregate uses
the observed-source RMS. A redundant block owner is omitted for a bare formula or
unnamed one-entry list and retained for explicitly named one-entry lists and
multiple components.
Value
A list of class summary_heterogeneity.brma containing:
-
estimates: ABayesTools_tablewith heterogeneity statistics -
component: The public heterogeneity-component name
For decomposed brma.mv() models with multiple selected components,
a named list of such summary objects is returned.
References
Higgins JP, Thompson SG (2002). “Quantifying heterogeneity in a meta-analysis.” Statistics in Medicine, 21(11), 1539–1558. doi:10.1002/sim.1186.
See Also
pooled_heterogeneity(), summary.brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
summary_heterogeneity(fit)
}
## End(Not run)
Summarize Model-Averaged Component Weights
Description
Creates marginal or individual model-weight summaries for RoBMA-class product-space objects.
Usage
summary_models(object, ...)
## S3 method for class 'RoBMA'
summary_models(object, type = "marginal", include_mcmc_diagnostics = TRUE, ...)
## S3 method for class 'summary_models.RoBMA'
print(x, ...)
Arguments
object |
a fitted RoBMA-class product-space object, including
|
... |
unused additional arguments. Supplied arguments trigger a warning. |
type |
whether to summarize marginal component prior distributions
( |
include_mcmc_diagnostics |
whether to include Bayes factor MCMC
diagnostics in the output. Defaults to |
x |
a |
Details
Model families include ordinary mixtures, spike-and-slab priors, and declared Bernoulli inclusion gates of random-effect components. Fixed components without a model choice are omitted.
Value
A list of class summary_models.RoBMA with elements
name and type. For type = "marginal", element
marginal contains component tables with columns such as
prior_prob, post_prob, and inclusion_BF. For
type = "individual", element individual contains individual
model combinations and posterior probabilities.
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- RoBMA(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
summary_models(fit)
summary_models(fit, type = "individual")
}
## End(Not run)
True Effects
Description
Computes the estimated true effects (theta) from a
fitted model. This is a separate S3 generic whose brma method
delegates to blup.brma.
Usage
true_effects(object, ...)
Arguments
object |
a fitted model object |
... |
additional arguments passed to methods |
Value
Method-specific return value, typically a summary table or posterior samples of BLUP or empirical-Bayes true-effect summaries.
See Also
True Effects for brma Objects
Description
Computes the estimated true effects (theta) for a
fitted brma object. This is an alias for blup.brma.
Usage
## S3 method for class 'brma'
true_effects(
object,
bias_adjusted = FALSE,
output_measure = NULL,
transform = NULL,
probs = c(0.025, 0.975),
...
)
Arguments
object |
a fitted brma object |
bias_adjusted |
whether to adjust for publication bias. Defaults to
|
output_measure |
effect-size measure for location/effect predictions.
Defaults to the fitted measure. Supported conversions are among |
transform |
optional display transformation. Currently |
probs |
quantiles of the posterior distribution to be displayed.
Defaults to |
... |
additional arguments passed to |
Details
This function is identical to blup.brma. See that function
for full details on how true effects are computed.
Value
A brma_samples object containing posterior draws of BLUP or
empirical-Bayes true-effect summaries with one column per estimate. For
existing normal data, these are conditional BLUP means, not simulated
latent-effect draws. When printed, displays a summary table. Use
summary(), or as.data.frame(summary(x)), to obtain the summary
table; as.data.frame(x) returns the posterior draws. The samples can be
converted to posterior draws formats using as_draws().
See Also
blup.brma(), predict.brma(), pooled_effect(),
pooled_heterogeneity()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- brma(
yi = yi,
vi = vi,
data = dat.lehmann2018,
measure = "SMD",
seed = 1,
silent = TRUE
)
true_effects(fit)
}
## End(Not run)
Update a brma Fit
Description
Extends an existing fitted brma object by additional MCMC samples,
updates study labels, and optionally recomputes cached fit-dependent
quantities.
Usage
## S3 method for class 'brma'
update(
object,
formula. = NULL,
...,
sample_extend = NULL,
slab = NULL,
autofit_control = NULL,
convergence_checks = NULL,
recompute = c("all", "drop"),
parallel = NULL,
cores = NULL,
silent = NULL,
evaluate = TRUE
)
Arguments
object |
a fitted |
formula. |
unsupported; included for compatibility with
|
... |
unsupported additional arguments. |
sample_extend |
integer. Number of additional samples per chain. |
slab |
optional character vector of study labels. Updating labels does not refit or extend the model. |
autofit_control |
list of autofit control settings. Values are merged with the existing settings before extending. |
convergence_checks |
list of convergence check settings. Values are merged with the existing settings and used to re-check the fit. |
recompute |
whether cached |
parallel |
logical. Whether to extend chains in parallel. |
cores |
integer. Number of cores to use when |
silent |
logical. Whether to suppress JAGS output during extension. |
evaluate |
unsupported; included for compatibility with
|
Details
Extending a fit preserves the fitted model and adds posterior samples. No
additional burn-in is requested. Rebuilding the compiled JAGS model, for
example after loading a saved fit, for parallel workers, or under runjags'
repeatable-method settings, can rerun adaptation before collecting those
samples. Retained selection caches store normalizer calculations, not JAGS
model pointers or sampler tuning. Prior, data, and model-structure updates are intentionally not
supported by this method. For brma.mv() objects, the stored V,
R, known-V backend, and marginalized random-effect metadata are
preserved because the fitted model structure is reused.
Extensions continue the random-number generator state stored by JAGS. They
cannot be restarted from a new seed without changing the meaning of chain
continuation, so update() has no seed argument.
Retained selection-normalizer caches are restored when compatible. Set
RoBMA.options(selection.cache_retain = TRUE) to retain the cache after
extension, or use remove_selection_cache() to remove saved cache entries.
Only explicitly stored selection-sensitivity diagnostics are refreshed after
chain extension, silently and using their stored simulation settings,
independently of recompute. Models without a stored comparison do not
compute one. Label-only updates retain the stored diagnostic. Use
selection_sensitivity_diagnostics() to inspect the refreshed result or error.
Named NULL elements in autofit_control and
convergence_checks explicitly disable or clear the corresponding
nullable setting. Omitted elements, a top-level NULL, and an empty
list() inherit the setting stored in object.
Value
The updated brma object.
Examples
## Not run:
fit <- update(fit, sample_extend = 1000)
fit <- update(fit, slab = paste("Study", seq_len(nobs(fit))))
## End(Not run)
Variance Inflation Factors
Description
Computes variance inflation factors (VIF) for a fitted model with moderators, to assess multicollinearity among predictors.
Usage
vif(object, ...)
Arguments
object |
a fitted model object |
... |
additional arguments passed to methods |
Value
Method-specific return value containing VIF diagnostics.
References
(Fox and Monette 1992)
See Also
Variance Inflation Factors for brma Objects
Description
Computes variance inflation factors (VIF) and generalized VIF (GVIF) for a fitted brma meta-regression model. Also optionally returns the posterior correlation matrix of regression coefficients.
Usage
## S3 method for class 'brma'
vif(
object,
posterior_correlation = TRUE,
max_samples = Inf,
...,
probs = NULL,
include_samples = FALSE
)
Arguments
object |
a fitted brma object with moderators |
posterior_correlation |
logical; whether to also compute and return
the posterior correlation matrix of regression coefficients. Defaults
to |
max_samples |
maximum posterior draws used for the VIF/GVIF
computation in every model class. Defaults to
|
... |
additional arguments (currently ignored) |
probs |
optional credible-interval probabilities for GVIF (ordinary
VIF for one-df terms). Defaults to |
include_samples |
whether to include a |
Details
VIF is computed from the correlation matrix derived from the
coefficient variance-covariance matrix (X'WX)^{-1}. For standard
meta-regression models, W = \mathrm{diag}(w_i/(v_i + \tau^2))
at each posterior heterogeneity draw. Scale and multilevel models use
observation-specific \tau_i and block-structured covariance where
applicable. VIF/GVIF and its adjusted root are computed in each draw and
averaged separately. These posterior means are generally different from
applying VIF to an averaged covariance or to a posterior-mean heterogeneity.
The mean adjusted GVIF is likewise generally different from transforming
the mean GVIF. The diagnostic retains its GLS design-based meaning; it is
not calculated from the empirical posterior covariance of the coefficients.
A VIF of 1 indicates no collinearity; values above 5 or 10 are commonly considered problematic.
The members of a RoBMA() ensemble can differ in their bias terms (PET
adds a PET column, PEESE a PEESE column, and the null and
weight-function members add none), so each posterior draw uses the design of
its member. A location term summarizes all selected posterior draws;
PET and PEESE summarize only draws in their own class
(NA when no selected draw belongs to it). Their samples are NA
outside that class, not zero, and their credible intervals are conditional
on class membership. Location terms keep the specified location design,
including terms with spike-and-slab priors.
For multi-column terms, such as factor contrasts,
the Generalized VIF (GVIF) of Fox and Monette (1992)
is reported. GVIF captures the joint inflation for all coefficients
belonging to the same term. To enable comparison across terms with different
degrees of freedom, GVIF^{1/(2 \cdot df)} is also reported; this
value can be compared against the usual VIF thresholds (after squaring).
When posterior_correlation = TRUE, the function also returns the
posterior correlation matrix of the regression coefficients. This
Bayesian diagnostic complements VIF: while VIF diagnoses the
potential for collinearity problems (a data property), the
posterior correlation shows the realized identification
given the data and priors. Informative priors can mitigate
collinearity, reducing posterior correlations even when VIF is high.
Data-only objects created with only_data = TRUE are rejected because
VIF depends on fitted heterogeneity information, not just the parsed data.
For brma.mv() known-V models, VIF is computed from the full
marginal GLS covariance. Formula random effects are marginalized through
BayesTools' random-effect covariance metadata rather than treated as
conditioned fitted effects.
For known-V models, the VIF requires applying the inverse of the
marginal covariance. A covariance that is too ill-conditioned for that (a
reciprocal condition number of about 2e-10 or less in any posterior
draw used) is unavailable: the call stops with an error of class
RoBMA_known_v_precision_unavailable, whose parent class is
RoBMA_numerical_unavailable, instead of returning a rounded number.
The condition carries the draw positions (rows) and their
reciprocal_condition.
For generalized linear mixed models, this is a working effect-size-scale diagnostic based on the fitted model's approximate sampling variances. It is not a VIF derived directly from the binomial or Poisson information matrix. When the marginal covariance is fixed, the calculation reduces to the conventional fixed-covariance VIF used by metafor.
Value
An object of class vif.brma containing:
vif |
A data frame with columns |
posterior_correlation |
A correlation matrix of posterior regression
coefficient samples when requested and available; otherwise |
samples |
The optional long data frame of draw-wise diagnostics when
|
References
Fox J, Monette G (1992). “Generalized collinearity diagnostics.” Journal of the American Statistical Association, 87(417), 178–183. doi:10.1080/01621459.1992.10475190.
See Also
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE) &&
requireNamespace("metafor", quietly = TRUE)) {
data(dat.bcg, package = "metadat")
dat <- metafor::escalc(
measure = "RR",
ai = tpos,
bi = tneg,
ci = cpos,
di = cneg,
data = dat.bcg
)
fit <- brma(
yi = yi,
vi = vi,
mods = ~ ablat + year,
data = dat,
measure = "RR",
seed = 1,
silent = TRUE
)
vif(fit)
}
## End(Not run)
WAIC for brma Objects
Description
Extract the WAIC object from a brma model object.
The WAIC must first be computed using add_waic.
Usage
## S3 method for class 'brma'
waic(x, unit = "estimate", ...)
Arguments
x |
a brma model object. |
unit |
output/deletion unit. See |
... |
additional arguments (currently unused). |
Details
This function extracts the WAIC object that was previously computed and
stored using object <- add_waic(object, unit = unit). If WAIC has not
been computed for the requested unit, an error is thrown.
This is the RoBMA S3 generic and brma method. The method is also
registered for waic, so loo::waic(fit) extracts
the cached WAIC object for brma fits. Use waic
directly for raw log-likelihood arrays or matrices.
In most cases, LOO-PSIS (via loo.brma) is preferred over WAIC
because it provides better estimates and includes diagnostics (Pareto k
values) that indicate when the approximation may be unreliable.
Value
An object of class "waic" as returned by
waic.
See Also
Plot Zplot Diagnostics Directly
Description
Convenience wrapper for creating and plotting zplot diagnostics
from a fitted brma object.
Usage
## S3 method for class 'brma'
zplot(
object,
significance_level = stats::qnorm(0.975),
summary_max_samples = 10000,
conditioning_depth = "marginal",
integration_control = set_selection_likelihood_control(),
...
)
## S3 method for class 'zplot_brma'
zplot(object, ...)
Arguments
object |
a normal-outcome |
significance_level |
positive z-value threshold for significance.
Defaults to |
summary_max_samples |
retained for compatibility and validated as a
posterior-sample budget, but unused by the default conversion path:
direct plotting does not compute EDR
or missing-study summaries. Use |
conditioning_depth |
predictive conditioning depth of the displayed
densities. Defaults to |
integration_control |
numerical integration settings created by
|
... |
arguments passed to |
Details
For models using the default as_zplot.brma() method, direct
plotting prepares the observed z-statistics and predictive target without
computing EDR or missing-study summary integrals. It uses
the same density computation and numerical checks as plot(as_zplot(object)).
A failure confined to a summary integral therefore does not prevent a plot;
density-integration failures still stop plotting. Use as_zplot()
followed by summary() to obtain the summaries.
Custom as_zplot() methods for subclasses retain their conversion
and plotting dispatch, including any summaries those methods compute.
When object already inherits from zplot_brma,
zplot() dispatches directly to plot.zplot_brma() without
recomputing stored summaries.
Value
NULL invisibly for base graphics, or a ggplot2 object.
See Also
as_zplot.brma(), plot.zplot_brma(), summary.zplot_brma()
Examples
## Not run:
if (requireNamespace("metadat", quietly = TRUE)) {
data(dat.lehmann2018, package = "metadat")
fit <- bPET(yi = yi, vi = vi, data = dat.lehmann2018, measure = "SMD")
zplot(fit)
}
## End(Not run)