Skip to content

Methods for fitted models

Functions that take a fitted model. Each is a single-dispatch function: the generic function chooses the implementation from the class of the fitted model, and the implementations are documented below the generic. A call with a class that has no implementation raises metafopy.errors.ArgumentError.

Predictions and intervals

predict

predict(
    model: Any, *args: Any, **kwargs: Any
) -> PredictResult

Predicted values for a fitted model, with confidence and prediction intervals (metafor's predict.rma).

This is a single-dispatch function: the implementation is chosen by the class of model. See predict_rma_uni, predict_rma_glmm, predict_rma_mv and predict_rma_ls for the arguments of each. The fits of rma_mh and rma_peto (predict_fixed_binary, the arguments of predict_rma_uni; newmods is not accepted), of selmodel and the results of matreg are also registered.

Parameters:

Name Type Description Default
model Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation (newmods first).

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
PredictResult

The predictions, a PredictResult.

Raises:

Type Description
ArgumentError

there is no implementation for the class of model. An argument the implementation does not have is a TypeError from Python, as for any function.

predict_rma_uni

predict_rma_uni(
    model: RMAResult,
    newmods: ArrayLike
    | Mapping[str, float]
    | Series
    | DataFrame
    | PairmatSpec
    | None = None,
    *,
    intercept: bool | None = None,
    tau2_levels: Sequence[str | int]
    | str
    | int
    | None = None,
    gamma2_levels: Sequence[str | int]
    | str
    | int
    | None = None,
    hetvar: ArrayLike | None = None,
    prob: str | float | None = None,
    addx: bool = False,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    level: float | None = None,
    adjust: bool = False,
    vcov: bool = False,
    predtype: str | None = None,
    pi_type: str | None = None,
    newvi: ArrayLike | None = None,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    digits: int | Mapping[str, int] | None = None,
    verbose: bool = False,
) -> PredictResult

Predicted values, standard errors, confidence intervals and prediction intervals for an rma_uni fit.

Without newmods an intercept-only model gives the pooled estimate and a meta-regression the fitted value of each study.

R source: https://github.com/wviechtb/metafor/blob/master/R/predict.rma.r

Parameters:

Name Type Description Default
model RMAResult

Model fitted by rma_uni.

required
newmods ArrayLike | Mapping[str, float] | Series | DataFrame | PairmatSpec | None

Moderator values of new studies to predict for, without the intercept column (it is added, see intercept) or with all p columns (then intercept is ignored, with a warning if given, and the first column decides whether the intercept is included). A number or 1-d array gives one prediction per value if the model has a single moderator and one prediction otherwise; a 2-d array gives one prediction per row. A dict, pandas Series or DataFrame with string names is matched by name to the moderators of the model when it has more than one moderator (a name may be shortened to any subsequence of the moderator name, as in metafor). The predictions are labelled by the index of a DataFrame with string index, or by the names of a dict or Series for a model with a single moderator, else by their position. A pairmat specification is also accepted. Factors must be given as the contrast variables of the model matrix. Models without moderators do not accept newmods. Default: no new values, so an intercept-only model gives the pooled estimate and a meta-regression the fitted value of every study.

None
intercept bool | None

Whether to include the intercept when predicting for newmods: if False, the intercept column is set to 0. Default: the column of ones is added if the model has an intercept. Ignored when newmods has all p columns.

None
tau2_levels Sequence[str | int] | str | int | None

Levels of the inner factor for the prediction interval. Accepted for compatibility with metafor; it has no effect for this model.

None
gamma2_levels Sequence[str | int] | str | int | None

Levels of the inner factor for the prediction interval. Accepted for compatibility with metafor; it has no effect for this model.

None
hetvar ArrayLike | None

Amount of heterogeneity to use in the prediction interval instead of the estimated tau^2: a number or one value per prediction (a different length raises InputError). Default: the estimate of the model.

None
prob str | float | None

Probability to add to the result, as a string such as '>0.2' or '<0': the probability that a true outcome is above (>) or below (<) the cutoff, from the predictive distribution (normal or t, see predtype). A number means >. The cutoff may be an arithmetic expression (+ - * / ^) using the constants pi and Inf and the functions abs, atanh, cos, exp, log, log10, log1p, log2, plogis, qlogis, sin, sqrt, tan and tanh, such as '>log(0.8)'; a string that is not such an expression gives no prob, as in metafor. Cannot be combined with adjust=True. Default: none.

None
addx bool

Add the model matrix of the predictions to the result (X).

False
transf Callable[..., Any] | None

Function applied to each predicted value and interval bound separately (for example numpy.exp); se is then NaN and the lower and upper bounds are put in order. Default: no transformation.

None
targs Any

Second argument passed to transf (transf(value, targs)). Default: none, except for the integral and mode transformations of transf, which get {'tau2': tau2}.

None
level float | None

Confidence and prediction interval level in percent (95 is 95%). As in metafor, a value below 1 is read as the confidence level if it is above 0.5 (0.95) and as the significance level otherwise (0.05). Default: the level of the model.

None
adjust bool

Apply a Bonferroni correction: the significance level is divided by the number of predictions, which widens the intervals.

False
vcov bool

Add the variance-covariance matrix of the predictions to the result (vcov; metafor returns it as a second list element). Ignored with transf.

False
predtype str | None

Type of prediction interval: 'default' (the normal distribution, or the t distribution with the degrees of freedom ddf of the test), 'simple' (ignore the uncertainty of the predicted value, normal distribution), 'riley' (t distribution with ddf - parms + p degrees of freedom, which is k - parms when ddf = k - p; Riley et al., 2011, doi:10.1136/bmj.d549) or 't' (t distribution with ddf degrees of freedom); degrees of freedom below 1 are set to 1. Case is ignored and a unique prefix is accepted. Default: pi_type, else 'default'.

None
pi_type str | None

Old spelling of predtype, used when predtype is None.

None
newvi ArrayLike | None

Sampling variances of the new studies, added to the variance of the prediction interval: a number or one value per prediction (a different length raises InputError). Default: 0.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit', 'exclude', 'pass' or 'fail' (metafor takes this from the na.action option). For the fitted values (no newmods) of a meta-regression, 'omit' returns the studies used in fitting, 'exclude' one row per study with NaN for those left out and 'pass' one row per study computed from the moderator values it has. 'fail' raises if any study was left out of the fit, also when newmods is given. Predictions for newmods drop ('omit') or keep ('exclude', 'pass') the rows that are NaN.

'omit'
digits int | Mapping[str, int] | None

Number of decimals used when printing, or a mapping with any of the keys est, se, test, pval, ci, var, sevar, fit and het (a unique prefix of a key is accepted). It is stored in the result and does not change the values. Default: the digits option, else that of the model.

None
verbose bool

Accepted for metafor's printing of the details of a failing clubSandwich contrast; it has no effect here.

False

Returns:

Type Description
PredictResult

The predictions, a PredictResult with pred, se, ci_lb, ci_ub, pi_lb and pi_ub (one entry per

PredictResult

prediction; the prediction interval is NaN where there is none), plus prob, X and vcov if requested. Unlike metafor, vcov is a

PredictResult

field of the result, not a second list element.

Raises:

Type Description
InputError

an argument or the data is invalid (for example prob with adjust=True, newmods of the wrong width or for a model without moderators, an unknown predtype or na_action, a hetvar or newvi of the wrong length, or a fit made robust with club_sandwich=True and the saddlepoint test).

Metafor reference

predict.rma

predict_rma_glmm

predict_rma_glmm(
    model: GLMMResult,
    newmods: ArrayLike
    | Mapping[str, float]
    | Series
    | DataFrame
    | PairmatSpec
    | None = None,
    *,
    intercept: bool | None = None,
    tau2_levels: Sequence[str | int]
    | str
    | int
    | None = None,
    gamma2_levels: Sequence[str | int]
    | str
    | int
    | None = None,
    hetvar: ArrayLike | None = None,
    prob: str | float | None = None,
    addx: bool = False,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    level: float | None = None,
    adjust: bool = False,
    vcov: bool = False,
    predtype: str | None = None,
    pi_type: str | None = None,
    newvi: ArrayLike | None = None,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    digits: int | Mapping[str, int] | None = None,
    verbose: bool = False,
) -> PredictResult

Predicted values for an rma_glmm fit (metafor's predict.rma; the arguments are those of predict_rma_uni).

The predictions are on the scale of the linear predictor of the model: with the default links, log odds ratios (measure='OR'), log incidence rate ratios ('IRR'), log odds ('PLO') or log incidence rates ('IRLN'); the experimental measures and a different link change the scale. Without newmods a meta-regression gives the fitted value of each study that entered the model. Prediction intervals add tau2 and are absent (NaN) for the fixed-effects methods.

R source: https://github.com/wviechtb/metafor/blob/master/R/predict.rma.r

Parameters:

Name Type Description Default
model GLMMResult

Model fitted by rma_glmm.

required
newmods ArrayLike | Mapping[str, float] | Series | DataFrame | PairmatSpec | None

Moderator values of new studies to predict for, without the intercept column (it is added, see intercept) or with all p columns (then intercept is ignored, with a warning if given, and the first column decides whether the intercept is included). A number or 1-d array gives one prediction per value if the model has a single moderator and one prediction otherwise; a 2-d array gives one prediction per row. A dict, pandas Series or DataFrame with string names is matched by name to the moderators of the model when it has more than one moderator (a name may be shortened to any subsequence of the moderator name, as in metafor). The predictions are labelled by the index of a DataFrame with string index, or by the names of a dict or Series for a model with a single moderator, else by their position. A pairmat specification is also accepted. Factors must be given as the contrast variables of the model matrix. Models without moderators do not accept newmods. Default: no new values, so an intercept-only model gives the pooled estimate and a meta-regression the fitted value of every study.

None
intercept bool | None

Whether to include the intercept when predicting for newmods: if False, the intercept column is set to 0. Default: the column of ones is added if the model has an intercept. Ignored when newmods has all p columns.

None
tau2_levels Sequence[str | int] | str | int | None

Levels of the inner factor for the prediction interval. Accepted for compatibility with metafor; it has no effect for this model.

None
gamma2_levels Sequence[str | int] | str | int | None

Levels of the inner factor for the prediction interval. Accepted for compatibility with metafor; it has no effect for this model.

None
hetvar ArrayLike | None

Amount of heterogeneity to use in the prediction interval instead of the estimated tau^2: a number or one value per prediction (a different length raises InputError). Default: the estimate of the model.

None
prob str | float | None

Probability to add to the result, as a string such as '>0.2' or '<0': the probability that a true outcome is above (>) or below (<) the cutoff, from the predictive distribution (normal or t, see predtype). A number means >. The cutoff may be an arithmetic expression (+ - * / ^) using the constants pi and Inf and the functions abs, atanh, cos, exp, log, log10, log1p, log2, plogis, qlogis, sin, sqrt, tan and tanh, such as '>log(0.8)'; a string that is not such an expression gives no prob, as in metafor. Cannot be combined with adjust=True. Default: none.

None
addx bool

Add the model matrix of the predictions to the result (X).

False
transf Callable[..., Any] | None

Function applied to each predicted value and interval bound separately (for example numpy.exp); se is then NaN and the lower and upper bounds are put in order. Default: no transformation.

None
targs Any

Second argument passed to transf (transf(value, targs)). Default: none, except for the integral and mode transformations of transf, which get {'tau2': tau2}.

None
level float | None

Confidence and prediction interval level in percent (95 is 95%). As in metafor, a value below 1 is read as the confidence level if it is above 0.5 (0.95) and as the significance level otherwise (0.05). Default: the level of the model.

None
adjust bool

Apply a Bonferroni correction: the significance level is divided by the number of predictions, which widens the intervals.

False
vcov bool

Add the variance-covariance matrix of the predictions to the result (vcov; metafor returns it as a second list element). Ignored with transf.

False
predtype str | None

Type of prediction interval: 'default' (the normal distribution, or the t distribution with the degrees of freedom ddf of the test), 'simple' (ignore the uncertainty of the predicted value, normal distribution), 'riley' (t distribution with ddf - parms + p degrees of freedom, which is k - parms when ddf = k - p; Riley et al., 2011, doi:10.1136/bmj.d549) or 't' (t distribution with ddf degrees of freedom); degrees of freedom below 1 are set to 1. Case is ignored and a unique prefix is accepted. Default: pi_type, else 'default'.

None
pi_type str | None

Old spelling of predtype, used when predtype is None.

None
newvi ArrayLike | None

Sampling variances of the new studies, added to the variance of the prediction interval: a number or one value per prediction (a different length raises InputError). Default: 0.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit', 'exclude', 'pass' or 'fail' (metafor takes this from the na.action option). For the fitted values (no newmods) of a meta-regression, 'omit' returns the studies used in fitting, 'exclude' one row per study with NaN for those left out and 'pass' one row per study computed from the moderator values it has. 'fail' raises if any study was left out of the fit, also when newmods is given. Predictions for newmods drop ('omit') or keep ('exclude', 'pass') the rows that are NaN.

'omit'
digits int | Mapping[str, int] | None

Number of decimals used when printing, or a mapping with any of the keys est, se, test, pval, ci, var, sevar, fit and het (a unique prefix of a key is accepted). It is stored in the result and does not change the values. Default: the digits option, else that of the model.

None
verbose bool

Accepted for metafor's printing of the details of a failing clubSandwich contrast; it has no effect here.

False

Returns:

Type Description
PredictResult

The predictions, a PredictResult with pred, se, ci_lb, ci_ub, pi_lb and pi_ub (one entry per

PredictResult

prediction; the prediction interval is NaN where there is none), plus prob, X and vcov if requested. Unlike metafor, vcov is a

PredictResult

field of the result, not a second list element.

Raises:

Type Description
InputError

an argument or the data is invalid (for example prob with adjust=True, newmods of the wrong width or for a model without moderators, an unknown predtype or na_action, or a hetvar or newvi of the wrong length).

Metafor reference

predict.rma

predict_rma_mv

predict_rma_mv(
    model: RMAMVResult,
    newmods: ArrayLike
    | Mapping[str, float]
    | Series
    | DataFrame
    | PairmatSpec
    | None = None,
    *,
    intercept: bool | None = None,
    tau2_levels: Sequence[str | int]
    | str
    | int
    | None = None,
    gamma2_levels: Sequence[str | int]
    | str
    | int
    | None = None,
    hetvar: ArrayLike | None = None,
    prob: str | float | None = None,
    addx: bool = False,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    level: float | None = None,
    adjust: bool = False,
    vcov: bool = False,
    predtype: str | None = None,
    pi_type: str | None = None,
    newvi: ArrayLike | None = None,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    digits: int | Mapping[str, int] | None = None,
    verbose: bool = False,
) -> PredictResult

Predicted values for an rma_mv fit (metafor's predict.rma; the arguments are those of predict_rma_uni unless stated).

Prediction intervals add the sum of the sigma2 values and, when present, the tau2 and gamma2 values selected via tau2_levels and gamma2_levels. They are NaN when several tau2 or gamma2 values exist and no levels are given. A model without moderators cannot be given newmods. For the fitted values of studies left out of the fit (na_action='pass'), the tau2 and gamma2 value of a study whose inner level is lost is NaN when the model has several of them.

R source: https://github.com/wviechtb/metafor/blob/master/R/predict.rma.r

Parameters:

Name Type Description Default
model RMAMVResult

Model fitted by rma_mv.

required
newmods ArrayLike | Mapping[str, float] | Series | DataFrame | PairmatSpec | None

Moderator values of new studies to predict for, without the intercept column (it is added, see intercept) or with all p columns (then intercept is ignored, with a warning if given, and the first column decides whether the intercept is included). A number or 1-d array gives one prediction per value if the model has a single moderator and one prediction otherwise; a 2-d array gives one prediction per row. A dict, pandas Series or DataFrame with string names is matched by name to the moderators of the model when it has more than one moderator (a name may be shortened to any subsequence of the moderator name, as in metafor). The predictions are labelled by the index of a DataFrame with string index, or by the names of a dict or Series for a model with a single moderator, else by their position. A pairmat specification is also accepted. Factors must be given as the contrast variables of the model matrix. Models without moderators do not accept newmods. Default: no new values, so an intercept-only model gives the pooled estimate and a meta-regression the fitted value of every study.

None
intercept bool | None

Whether to include the intercept when predicting for newmods: if False, the intercept column is set to 0. Default: the column of ones is added if the model has an intercept. Ignored when newmods has all p columns.

None
tau2_levels Sequence[str | int] | str | int | None

Which tau2 value(s) to use in the prediction interval when the model has several: labels of the inner factor of the first inner | outer term or 0-based positions (a single value, used for every prediction, or a sequence with one per prediction). Default: none. With newmods and several tau2 values the prediction intervals are then NaN (metafor requires the levels). With the fitted values of a meta-regression the levels are those of the studies and tau2_levels is ignored (with a warning). For an intercept-only model metafor then returns one prediction for each tau2 value, whereas metafopy returns a single prediction with a NaN prediction interval.

None
gamma2_levels Sequence[str | int] | str | int | None

As tau2_levels, for the gamma2 values (second inner | outer term).

None
hetvar ArrayLike | None

Amount of heterogeneity to use in the prediction interval instead of the sum of the variance components: a number or one value per prediction (a different length raises InputError). tau2_levels and gamma2_levels are then ignored (with a warning).

None
prob str | float | None

Probability to add to the result, as a string such as '>0.2' or '<0': the probability that a true outcome is above (>) or below (<) the cutoff, from the predictive distribution (normal or t, see predtype). A number means >. The cutoff may be an arithmetic expression (+ - * / ^) using the constants pi and Inf and the functions abs, atanh, cos, exp, log, log10, log1p, log2, plogis, qlogis, sin, sqrt, tan and tanh, such as '>log(0.8)'; a string that is not such an expression gives no prob, as in metafor. Cannot be combined with adjust=True. Default: none.

None
addx bool

Add the model matrix of the predictions to the result (X).

False
transf Callable[..., Any] | None

Function applied to each predicted value and interval bound separately (for example numpy.exp); se is then NaN and the lower and upper bounds are put in order. Default: no transformation.

None
targs Any

Second argument passed to transf (transf(value, targs)). Default: none, except for the integral and mode transformations of transf, which get {'tau2': tau2}.

None
level float | None

Confidence and prediction interval level in percent (95 is 95%). As in metafor, a value below 1 is read as the confidence level if it is above 0.5 (0.95) and as the significance level otherwise (0.05). Default: the level of the model.

None
adjust bool

Apply a Bonferroni correction: the significance level is divided by the number of predictions, which widens the intervals.

False
vcov bool

Add the variance-covariance matrix of the predictions to the result (vcov; metafor returns it as a second list element). Ignored with transf.

False
predtype str | None

Type of prediction interval: 'default' (the normal distribution, or the t distribution with the degrees of freedom ddf of the test), 'simple' (ignore the uncertainty of the predicted value, normal distribution), 'riley' (t distribution with ddf - parms + p degrees of freedom, which is k - parms when ddf = k - p; Riley et al., 2011, doi:10.1136/bmj.d549) or 't' (t distribution with ddf degrees of freedom); degrees of freedom below 1 are set to 1. Case is ignored and a unique prefix is accepted. Default: pi_type, else 'default'.

None
pi_type str | None

Old spelling of predtype, used when predtype is None.

None
newvi ArrayLike | None

Sampling variances of the new studies, added to the variance of the prediction interval: a number or one value per prediction (a different length raises InputError). Default: 0.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit', 'exclude', 'pass' or 'fail' (metafor takes this from the na.action option). For the fitted values (no newmods) of a meta-regression, 'omit' returns the studies used in fitting, 'exclude' one row per study with NaN for those left out and 'pass' one row per study computed from the moderator values it has. 'fail' raises if any study was left out of the fit, also when newmods is given. Predictions for newmods drop ('omit') or keep ('exclude', 'pass') the rows that are NaN.

'omit'
digits int | Mapping[str, int] | None

Number of decimals used when printing, or a mapping with any of the keys est, se, test, pval, ci, var, sevar, fit and het (a unique prefix of a key is accepted). It is stored in the result and does not change the values. Default: the digits option, else that of the model.

None
verbose bool

Accepted for metafor's printing of the details of a failing clubSandwich contrast; it has no effect here.

False

Returns:

Type Description
PredictResult

The predictions, a PredictResult with pred, se, ci_lb, ci_ub, pi_lb and pi_ub (one entry per

PredictResult

prediction; the prediction interval is NaN where there is none), plus prob, X and vcov if requested. Unlike metafor, vcov is a

PredictResult

field of the result, not a second list element.

Raises:

Type Description
InputError

an argument or the data is invalid (for example newmods for a model without moderators, a level in tau2_levels or gamma2_levels that does not exist or a sequence of the wrong length, prob with adjust=True, an unknown predtype or na_action, or a hetvar or newvi of the wrong length).

Metafor reference

predict.rma

predict_rma_ls

predict_rma_ls(
    model: RMALSResult,
    newmods: ArrayLike | PairmatSpec | None = None,
    *,
    intercept: bool | None = None,
    addx: bool = False,
    newscale: ArrayLike | None = None,
    addz: bool = False,
    prob: str | None = None,
    level: float | None = None,
    adjust: bool = False,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    vcov: bool = False,
    predtype: str | None = None,
    pi_type: str | None = None,
    newvi: ArrayLike | None = None,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    digits: int | Mapping[str, int] | None = None,
    verbose: bool = False,
) -> LSPredictResult

Predicted values for a location-scale model, fitted by rma_uni with scale (metafor's predict.rma.ls).

What is predicted depends on the arguments. Without newmods and newscale the result holds the fitted values of the studies, with prediction intervals that use the tau^2 of each study. With newmods only it holds the predicted effects with confidence intervals; the prediction intervals are NaN, since tau^2 is not known for the new studies. With both it holds the predicted effects with confidence and prediction intervals, using the tau^2 predicted from newscale. With newscale only, pred holds the predicted log(tau^2) (log link) or tau^2 (identity link), pred_type is 'scale' and the prediction intervals are NaN (use transf=numpy.exp for tau^2 under the log link). With the identity link and no transf, negative predicted tau^2 values are set to 0 with a warning.

R source: https://github.com/wviechtb/metafor/blob/master/R/predict.rma.r

Parameters:

Name Type Description Default
model RMALSResult

Location-scale model fitted by rma_uni with scale.

required
newmods ArrayLike | PairmatSpec | None

Moderator values of new studies to predict for, without the intercept column (it is added, see intercept) or with all p columns (then intercept is ignored, with a warning if given). A number or 1-d array gives one prediction per value if the model has a single moderator and one prediction otherwise; a 2-d array gives one prediction per row. A dict, pandas Series or DataFrame with string names is matched by name to the moderators of the model when it has more than one moderator (a name may be shortened to any subsequence of the moderator name, as in metafor). A pairmat specification is also accepted. Factors must be given as the contrast variables of the model matrix. A model without moderators accepts only newmods=1. Default: none (the fitted values of the studies if newscale is not given either).

None
intercept bool | None

Whether to include the intercept when predicting for newmods (and newscale if newmods is not given): if False, the intercept column is set to 0. Default: the column of ones is added if the model has an intercept. Ignored when the matrix has all its columns; the intercept column of newscale is always 1 when newmods is given too.

None
addx bool

Add the model matrix of the predictions to the result (X).

False
newscale ArrayLike | None

Values of the scale variables of the new studies, without the intercept column (added, see intercept) or with all q columns; same forms as newmods. A model without scale variables accepts only newscale=1. If both are given, they must have the same number of rows, except that a single row of either is repeated. Default: none (see the description).

None
addz bool

Add the model matrix of the scale variables of the predictions to the result (Z).

False
prob str | None

Probability to add to the result, as a string such as '>0.2' or '<0': the probability that a true outcome is above (>) or below (<) the cutoff, from the predictive distribution (normal or t, see predtype). The cutoff may be an arithmetic expression as for predict; a string that is not one gives no prob. Not computed for scale predictions (newscale only). Cannot be combined with adjust=True. Default: none.

None
level float | None

Confidence and prediction interval level in percent (95 is 95%). As in metafor, a value below 1 is read as the confidence level if it is above 0.5 (0.95) and as the significance level otherwise (0.05). Default: the level of the model.

None
adjust bool

Apply a Bonferroni correction: the significance level is divided by the number of predictions, which widens the intervals.

False
transf Callable[..., Any] | None

Function applied to each predicted value and interval bound separately (for example numpy.exp); se is then NaN and the lower and upper bounds are put in order. Default: no transformation.

None
targs Any

Second argument passed to transf (transf(value, targs)). Default: none; unlike for predict of an rma_uni fit, the integral and mode transformations get no default tau2.

None
vcov bool

Add the variance-covariance matrix of the predictions to the result (vcov; metafor returns it as a second list element). Ignored with transf.

False
predtype str | None

Type of prediction interval: 'default' (the normal distribution, or the t distribution with k - p degrees of freedom if the test is 't', 'knha' or 'adhoc'), 'simple' (ignore the uncertainty of the predicted value, normal distribution), 'riley' (t distribution with k - p - q degrees of freedom, Riley et al., 2011, doi:10.1136/bmj.d549) or 't' (t distribution with k - p degrees of freedom); degrees of freedom below 1 are set to 1. Case is ignored and a unique prefix is accepted. Default: pi_type, else 'default'.

None
pi_type str | None

Old spelling of predtype, used when predtype is None.

None
newvi ArrayLike | None

Sampling variances of the new studies, added to the variance of the prediction interval: a number or one value per prediction. Default: 0.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit', 'exclude', 'pass' or 'fail' (metafor takes this from the na.action option). For the fitted values (no newmods or newscale), 'omit' returns the studies used in fitting, 'exclude' one row per study with NaN for those left out and 'pass' one row per study computed from the values it has. 'fail' raises if any study was left out of the fit, also when newmods or newscale is given. Predictions for newmods or newscale drop ('omit') or keep ('exclude', 'pass') the rows that are NaN.

'omit'
digits int | Mapping[str, int] | None

Number of decimals used when printing, or a mapping with any of the keys est, se, test, pval, ci, var, sevar, fit and het (a unique prefix of a key is accepted). It is stored in the result and does not change the values. Default: the digits option, else that of the model.

None
verbose bool

Accepted for compatibility with metafor; it has no effect here.

False

Returns:

Type Description
LSPredictResult

The predictions, an LSPredictResult: a PredictResult with the extra fields Z (the scale model matrix, with

LSPredictResult

addz=True; None otherwise) and z_names. pred_type is 'location' or 'scale'; the predicted tau^2 of a scale prediction is

LSPredictResult

in pred (there is no tau2 field). ddf is a single number, None if the test is 'z'. Unlike metafor, vcov is a field of the

LSPredictResult

result, not a second list element.

Raises:

Type Description
InputError

an argument is invalid (for example prob with adjust=True, an unknown predtype or na_action, a newvi of the wrong length, moderator or scale values for a model without them), or the dimensions of newmods or newscale do not match the model or each other.

Metafor reference

predict.rma

PredictResult dataclass

PredictResult(
    pred: FloatArray,
    se: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    pi_lb: FloatArray,
    pi_ub: FloatArray,
    slab: tuple[str, ...] | None = None,
    pi_se: FloatArray | None = None,
    pi_dist: str | None = None,
    pi_ddf: float | FloatArray | None = None,
    ddf: float | FloatArray | None = None,
    has_pi: bool = True,
    prob: FloatArray | None = None,
    X: FloatArray | DataFrame | None = None,
    vcov: FloatArray | DataFrame | None = None,
    x_names: tuple[str, ...] | None = None,
    digits: int = 4,
    digit_map: Mapping[str, int] | None = None,
    method: str | None = None,
    transf: bool = False,
    pred_type: str = 'location',
)

Predictions with confidence (ci) and prediction (pi) intervals, as returned by predict. Use to_frame() for a data frame and str() for the printout of metafor's print.list.rma.

Attributes:

Name Type Description
pred FloatArray

Predicted values, one per prediction.

se FloatArray

Standard errors of the predicted values; NaN when a transformation was applied, as in metafor.

ci_lb FloatArray

Lower bounds of the confidence intervals.

ci_ub FloatArray

Upper bounds of the confidence intervals.

pi_lb FloatArray

Lower bounds of the prediction intervals (cr_lb is an alias); NaN where there is no prediction interval (the equal-effects methods, an integral or mode transformation of an rma_uni or rma_glmm fit).

pi_ub FloatArray

Upper bounds of the prediction intervals (cr_ub is an alias); NaN where there is no prediction interval.

slab tuple[str, ...] | None

Labels of the predictions, or None. A single prediction without a name has the label ''.

pi_se FloatArray | None

Standard errors of the predictions (before any transformation).

pi_dist str | None

Distribution of the prediction, 'norm' or 't' (used by forest(predstyle='shade') and 'dist').

pi_ddf float | FloatArray | None

Degrees of freedom of the prediction distribution, one per prediction; None when pi_dist is 'norm'.

ddf float | FloatArray | None

Degrees of freedom of the confidence intervals, one per prediction (a single number for location-scale models); None when the normal distribution is used (for rma_mv fits: when the prediction interval uses it).

has_pi bool

Whether the model has prediction intervals (False for the equal-effects models of rma_mh and rma_peto).

prob FloatArray | None

Probabilities requested via prob; None if not requested or if the cutoff could not be evaluated.

X FloatArray | DataFrame | None

Model matrix of the predictions (addx=True, else None); a data frame for matreg predictions.

vcov FloatArray | DataFrame | None

Variance-covariance matrix of the predictions (vcov=True without transf, else None); a data frame for matreg predictions.

x_names tuple[str, ...] | None

Column names of X.

digits int

Number of decimals used when printing.

digit_map Mapping[str, int] | None

Decimals by kind of number (est, se, ci, ...), if the digits were given by kind.

method str | None

Estimation method of the model ('FE' for the rma_mh and rma_peto fits).

transf bool

Whether a transformation was applied.

pred_type str

'location' (predicted effects), or 'scale' for the predicted tau^2 values (log(tau^2) with a log link) of a location-scale model.

cr_lb property

cr_lb: FloatArray

Alias of pi_lb (metafor keeps cr.lb for old code).

cr_ub property

cr_ub: FloatArray

Alias of pi_ub (metafor keeps cr.ub for old code).

__post_init__

__post_init__() -> None

Give the model matrix its column names and vcov the prediction labels as its dimnames, as metafor's predict does.

__getitem__

__getitem__(index: Any) -> Self

The rows index (metafor's [.list.rma; a NumPy index, 0-based).

with_digits

with_digits(digits: Any) -> Self

The result printed with digits (a number, or a mapping with any of the keys of :data:metafopy.mfopt.DIGIT_KEYS).

__str__

__str__() -> str

The predictions as print.list.rma shows them: fixed decimals (digits), one row per prediction.

confint

confint(model: Any, *args: Any, **kwargs: Any) -> Any

Confidence intervals for the coefficients and variance components of a fitted model (metafor's confint).

This is a single-dispatch function: the implementation is chosen by the class of model. See confint_rma_uni, confint_rma_mv, confint_rma_ls and confint_fixed_binary; selection model fits (selmodel) are registered too.

Parameters:

Name Type Description Default
model Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation.

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
Any

The intervals, a ConfintResult (a ConfintList, a list of them, for some rma_mv, location-scale and selection

Any

model requests).

Raises:

Type Description
ArgumentError

there is no implementation for the class of model (for example an rma_glmm fit, as in metafor). An argument the implementation does not have is a TypeError from Python, as for any function.

confint_rma_uni

confint_rma_uni(
    model: RMAResult,
    *,
    fixed: bool = False,
    random: bool = True,
    type: CIType | None = None,
    level: float | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    tau2_min: float | None = None,
    tau2_max: float | None = None,
    tol: float = DEFAULT_TOL,
    maxiter: int = 1000,
    verbose: bool | int = False,
    digits: int | None = None,
    control: Mapping[str, Any] | None = None,
    xlim: float | Sequence[float] | None = None,
    extint: bool = False,
    parm: Any = None,
) -> ConfintResult

Confidence intervals for the coefficients and for tau^2, I^2 and H^2 of an rma_uni fit (metafor's confint.rma.uni).

The interval for tau^2 is found by root finding (Q-profile, generalised Q, profile likelihood or the Higgins-Thompson method) or is of Wald type; the bounds of I^2 and H^2 follow from those of tau^2.

R source: https://github.com/wviechtb/metafor/blob/master/R/confint.rma.uni.r

Parameters:

Name Type Description Default
model RMAResult

Model fitted by rma_uni.

required
fixed bool

Give Wald-type intervals for the coefficients (fixed table of the result), using the t distribution with the degrees of freedom of the test if the model uses it, else the normal distribution.

False
random bool

Give intervals for tau^2 (and tau), I^2 and H^2 (random table). At least one of fixed and random must be True.

True
type CIType | None

Method for the interval of tau^2 (case is ignored; any other value raises InputError): 'qp' (Q-profile, Viechtbauer, 2007, doi:10.1002/sim.2514; needs positive sampling variances), 'genq' (generalised Q, Jackson, 2013, doi:10.1002/jrsm.1081; needs a GENQ or GENQM fit), 'pl' (profile likelihood, which metafor suggests for ML and REML fits; the likelihood used is the REML one for method='REML' and the ML one otherwise), 'ht' (the test-based method of Higgins and Thompson, 2002, doi:10.1002/sim.1186; only for models without moderators and k > 2), or a Wald type 'wald', 'wald.log' or 'wald.sqrt' (in the metafor source but not described on its reference page). Default: 'genq' for GENQ and GENQM fits, else 'qp'.

None
level float | None

Confidence level in percent (95 is 95%). As in metafor, a value below 1 is read as the confidence level if it is above 0.5 (0.95) and as the significance level otherwise (0.05). Default: the level of the model.

None
transf Callable[..., Any] | None

Function applied to each coefficient and bound of the fixed table separately, for example numpy.exp; the bounds are put in order. Default: none.

None
targs Any

Second argument passed to transf (transf(value, targs)). Default: none, except for the integral and mode transformations of transf, which get {'tau2': tau2}.

None
tau2_min float | None

Lower end of the interval searched for the bounds of tau^2. Default: the smaller of 0 and the estimate (metafor uses the tau2.min of the control of the fitted model instead if it was set; metafopy does not). Replaced by the entry of control or by xlim.

None
tau2_max float | None

Upper end of the interval searched for the bounds. Default: the largest of 100, ten times the estimate and ten times the lower end.

None
tol float

Convergence tolerance of the root finding (default eps^0.25). Not used for type='genq', which uses the defaults of R's uniroot as metafor does.

DEFAULT_TOL
maxiter int

Maximum number of iterations of the root finding (not used for type='genq').

1000
verbose bool | int

Print the steps of the root finding for the types 'qp', 'genq' and 'pl' on stdout, as metafor does; with digits decimals.

False
digits int | None

Number of decimals used for verbose output and the printout of the result. Default: the digits option, else that of the model.

None
control Mapping[str, Any] | None

metafor's list of root-finding settings (tau2_min, tau2_max, tol and maxiter, written with . or _). Its entries replace the keyword arguments of the same name. Names must be given in full (metafor accepts partial names); entries that only other functions of metafor read, including verbose, are ignored here, and any other entry raises InputError.

None
xlim float | Sequence[float] | None

Interval (tau2_min, tau2_max) searched for the bounds (metafor's ... argument); a single value is the upper limit and the lower one is 0. Wins over control.

None
extint bool

Let the search for a profile-likelihood bound (type='pl') widen the interval (R's extendInt; metafor's ... argument).

False
parm Any

Ignored, with a warning, as in metafor.

None

Returns:

Type Description
ConfintResult

A ConfintResult with the fixed table (coefficients) and/or the random table (tau^2, tau, I^2(%),

ConfintResult

H^2), each with the columns estimate, ci.lb and ci.ub. A bound the search cannot find is NaN, with a warning.

Raises:

Type Description
InputError

an argument is invalid (unknown type or control entry, neither fixed nor random, xlim of the wrong length, a search interval that does not contain the estimate for type='pl', type='genq' for a fit that is not GENQ or GENQM, type='ht' with moderators or k <= 2, type='qp' with non-positive sampling variances), k = 1, or the model has no estimated random-effects component (equal-effects methods, or a fixed tau^2).

Metafor reference

confint.rma

confint_rma_mv

confint_rma_mv(
    model: RMAMVResult,
    *,
    fixed: bool = False,
    sigma2: int | None = None,
    tau2: int | None = None,
    rho: int | None = None,
    gamma2: int | None = None,
    phi: int | None = None,
    level: float | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    vc_min: float | None = None,
    vc_max: float | None = None,
    tol: float = DEFAULT_TOL,
    maxiter: int = 1000,
    eptries: int = 10,
    verbose: bool | int = False,
    digits: int | None = None,
    control: Mapping[str, Any] | None = None,
    xlim: Sequence[float] | None = None,
    extint: bool = False,
    parm: Any = None,
) -> ConfintResult | ConfintList

Confidence intervals for the variance and correlation components, or the coefficients, of an rma_mv fit (metafor's confint.rma.mv).

The intervals of the components are profile-likelihood intervals (Hardy and Thompson, 1996, doi:10.1002/(SICI)1097-0258(19960330)15:6<619::AID-SIM188>3.0.CO;2-A).

R source: https://github.com/wviechtb/metafor/blob/master/R/confint.rma.mv.r

Parameters:

Name Type Description Default
model RMAMVResult

Model fitted by rma_mv.

required
fixed bool

Give Wald-type intervals for the coefficients (t distribution with the degrees of freedom of each coefficient unless the test is 'z'). Without a component argument only these are returned; with one, the interval of the component is returned too.

False
sigma2 int | None

0-based position of the sigma2 component to compute the interval for. Only one of sigma2, tau2, rho, gamma2 and phi may be given.

None
tau2 int | None

0-based position of the tau2 component.

None
rho int | None

0-based position of the rho component.

None
gamma2 int | None

0-based position of the gamma2 component.

None
phi int | None

0-based position of the phi component.

None
level float | None

Confidence level in percent (95 is 95%). As in metafor, a value below 1 is read as the confidence level if it is above 0.5 (0.95) and as the significance level otherwise (0.05). Default: the level of the model.

None
transf Callable[..., Any] | None

Function applied to each coefficient and bound (with fixed=True) separately; the bounds are put in order. Default: none.

None
targs Any

Second argument passed to transf (transf(value, targs)). Default: none, except for the integral and mode transformations of transf, which get {'tau2': 0}.

None
vc_min float | None

Lower end of the interval searched for the bounds of a component. Default: 0 for sigma2, tau2 and gamma2; for rho and phi -1, except min(0, estimate) for the structures 'AR', 'HAR' and 'CAR' and 0 for the spatial structures. Replaced by control or xlim.

None
vc_max float | None

Upper end of the interval searched for the bounds. Default: for sigma2, tau2 and gamma2 the larger of 10 and 100 times the estimate (10 if the estimate is practically 0); for rho and phi 1, except max(10, 10 * estimate) for the structures 'SPEXP', 'SPGAU', 'SPLIN', 'SPRAT' and 'SPSPH' and max(2, 2 * estimate) for 'PHYPL' and 'PHYPD'.

None
tol float

Convergence tolerance of the root finding (default eps^0.25).

DEFAULT_TOL
maxiter int

Maximum number of iterations of the root finding.

1000
eptries int

Number of attempts to find the bounds: when the model cannot be fitted at an end of the interval searched, that end is moved towards the estimate by 1 / eptries of the distance and tried again.

10
verbose bool | int

Print the steps of the root finding on stdout, with digits decimals.

False
digits int | None

Number of decimals used for verbose output and the printout. Default: the digits option, else that of the model.

None
control Mapping[str, Any] | None

metafor's list of settings (vc_min, vc_max, tol, maxiter and eptries, written with . or _). Its entries replace the keyword arguments of the same name. Names must be given in full; entries that only other functions of metafor read, including verbose, are ignored here, and any other entry raises InputError.

None
xlim Sequence[float] | None

Interval (vc_min, vc_max) searched for the bounds (metafor's ... argument). Wins over control.

None
extint bool

Let the search for a bound widen the interval (R's extendInt).

False
parm Any

Ignored, with a warning, as in metafor.

None

Returns:

Type Description
ConfintResult | ConfintList

A ConfintResult for the requested component and/or the coefficients (fixed=True). With neither given, one result

ConfintResult | ConfintList

per estimated component in a ConfintList (a list, in the order sigma2, tau2, rho, gamma2, phi), or a single result if

ConfintResult | ConfintList

there is only one component. Tables have the columns estimate, ci.lb and ci.ub; a bound the search cannot find is NaN, with a

ConfintResult | ConfintList

warning.

Raises:

Type Description
InputError

more than one component argument is given, the model has no such (estimated) component or it was fixed, the interval searched does not contain the estimate, xlim is not of length 2, control has an unknown entry, or the model has no component to give an interval for.

Metafor reference

confint.rma

confint_rma_ls

confint_rma_ls(
    model: RMALSResult,
    *,
    fixed: bool = False,
    alpha: int | None = None,
    level: float | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    control: Mapping[str, Any] | None = None,
    tol: float = DEFAULT_TOL,
    maxiter: int = 1000,
    eptries: int = 10,
    xlim: Sequence[float] | None = None,
    extint: bool = False,
    parm: Any = None,
    digits: int | None = None,
    verbose: bool = False,
) -> ConfintResult | ConfintList

Confidence intervals for the scale (or location) coefficients of a location-scale model (metafor's confint.rma.ls).

Intervals for the scale coefficients are profile-likelihood intervals. The intervals for the location coefficients (fixed=True) are of Wald type.

Parameters:

Name Type Description Default
model RMALSResult

Location-scale model fitted by rma_uni with scale.

required
fixed bool

Give Wald-type intervals for the location coefficients (t distribution if the test is 't', 'knha' or 'adhoc', else normal). Without alpha only these are returned; with alpha, the interval of the scale coefficient is returned too.

False
alpha int | None

0-based position of the scale coefficient to compute the profile-likelihood interval for. Default: all estimated scale coefficients (unless fixed=True).

None
level float | None

Confidence level in percent (95 is 95%). As in metafor, a value below 1 is read as the confidence level if it is above 0.5 (0.95) and as the significance level otherwise (0.05). Default: the level of the model.

None
transf Callable[..., Any] | None

Function applied to each location coefficient and bound (with fixed=True) separately; the bounds are put in order. Default: none.

None
targs Any

Second argument passed to transf (transf(value, targs)). Default: none (the integral and mode transformations get no default tau2).

None
control Mapping[str, Any] | None

Settings of the root finding: vc_min and vc_max (also written vc.min, vc.max; the interval searched for the bounds), tol, maxiter, eptries and verbose (the entry verbose has no effect, see verbose). Its entries replace the keyword arguments of the same name. Names must be given in full; entries that only other functions of metafor read are ignored and any other entry raises InputError. The default interval searched for the bounds of a coefficient is its estimate plus and minus the smaller of ten times its absolute value and ten times the normal critical value times its standard error (the former only if the standard error is NaN), limited by alpha_min and alpha_max of the control of the fitted model.

None
tol float

Convergence tolerance of the root finding (default eps^0.25).

DEFAULT_TOL
maxiter int

Maximum number of iterations of the root finding.

1000
eptries int

Number of attempts to find the bounds: when the model cannot be fitted at an end of the interval searched, that end is moved towards the estimate by 1 / eptries of the distance and tried again.

10
xlim Sequence[float] | None

Interval (vc_min, vc_max) searched for the bounds (metafor's ... argument). Wins over control.

None
extint bool

Let the search for a bound widen the interval (R's extendInt).

False
parm Any

Ignored, with a warning, as in metafor.

None
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
verbose bool

Accepted for compatibility with metafor; it has no effect here (no output is produced).

False

Returns:

Type Description
ConfintResult | ConfintList

A ConfintResult with the estimate, ci.lb and ci.ub of the requested coefficient(s); the scale coefficient

ConfintResult | ConfintList

is in the random table (rows alpha.1, alpha.2, ...) and the location coefficients in the fixed table. With no alpha and

ConfintResult | ConfintList

several estimated scale coefficients, a ConfintList (a list of results); a single result if there is one. A bound the search cannot find

ConfintResult | ConfintList

is NaN, with a warning; a bound at the end of the interval searched is shown with a < or > sign.

Raises:

Type Description
InputError

an argument is invalid, control has an unknown entry, the model was fitted with optbeta=True, the model has no such (estimated) scale coefficient or no coefficient to give an interval for, or the interval searched does not contain the estimate.

Metafor reference

confint.rma

confint_fixed_binary

confint_fixed_binary(
    model: FixedBinaryResult,
    *,
    level: float | None = None,
    transf: Callable[..., Any] | bool | None = None,
    targs: Any = None,
    digits: int | None = None,
    parm: Any = None,
) -> ConfintResult

Wald-type confidence interval of the pooled effect of an rma_mh or rma_peto fit (metafor's confint.rma.mh and confint.rma.peto).

Parameters:

Name Type Description Default
model FixedBinaryResult

Model fitted by rma_mh or rma_peto.

required
level float | None

Confidence level in percent (95 is 95%). As in metafor, a value below 1 is read as the confidence level if it is above 0.5 (0.95) and as the significance level otherwise (0.05). Default: the level of the model.

None
transf Callable[..., Any] | bool | None

Function applied to the estimate and each bound separately (for example numpy.exp); the bounds are put in order. True applies numpy.exp when the measure is 'OR', 'RR', 'IRR' or Peto's odds ratio ('PETO') and no transformation for other measures. Default: none.

None
targs Any

Second argument passed to transf (transf(value, targs)). Default: none.

None
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
parm Any

Ignored, with a warning, as in metafor.

None

Returns:

Type Description
ConfintResult

A ConfintResult whose fixed table has one row, with an empty label, and the columns estimate, ci.lb and

ConfintResult

ci.ub; the interval uses the normal distribution.

Metafor reference

confint.rma

ConfintResult dataclass

ConfintResult(
    fixed: DataFrame | None,
    random: DataFrame | None,
    lb_sign: str = '',
    ub_sign: str = '',
    digits: int | None = None,
    tau2_min: float | None = None,
)

Bases: HtmlRepr

Confidence intervals as returned by confint: a fixed table for the coefficients and/or a random table for the variance components. to_frame() stacks the tables and summary() gives metafor's printout.

Attributes:

Name Type Description
fixed DataFrame | None

Table of the coefficients (fixed=True) with the columns estimate, ci.lb and ci.ub, one row per coefficient, or None.

random DataFrame | None

Table of the variance components with the same columns, or None. The rows are tau^2, tau, I^2(%) and H^2 for an rma_uni fit; for an rma_mv fit sigma^2 and sigma, tau^2 and tau or gamma^2 and gamma (one pair), or rho or phi (one row), with the position added (.1, .2, ...) if the model has several; for a location-scale fit alpha.1, alpha.2, ... (alpha if there is one).

lb_sign str

Prefix printed before the lower bounds of random: '<' if the bound lies below the lower end of the interval searched, '>' if it lies above the upper end, else ''.

ub_sign str

Prefix printed before the upper bounds of random, as lb_sign.

digits int | None

Number of decimals used when printing (None if not set).

tau2_min float | None

Lower end of the interval searched for the bounds of tau^2 (rma_uni fits with random=True, else None).

ci_null property

ci_null: bool

metafor's ci.null: the whole interval of the variance component lies at or below the lower limit of the search (that limit is zero or less).

to_frame

to_frame() -> DataFrame

The fixed and random tables stacked into one data frame (the columns are estimate, ci.lb and ci.ub).

summary

summary(
    digits: int | Mapping[str, int] | None = None,
) -> str

The printout of metafor's print.confint.rma: the table of the coefficients, then that of the variance components.

Tests and profiles

anova

anova(model: Any, *args: Any, **kwargs: Any) -> Any

Wald tests of coefficients or likelihood-ratio tests of nested models for fitted models (metafor's anova).

This is a single-dispatch function: the implementation is chosen by the class of model. See anova_rma_uni, anova_rma_mv and anova_rma_ls.

Parameters:

Name Type Description Default
model Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation (a second model first).

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
Any

A WaldResult (Wald test), an LRTResult (likelihood-ratio test of two rma_uni models), a

Any

MVLRTResult (likelihood-ratio test of two rma_mv or location-scale models), an LSWaldResult (Wald test for a location-scale

Any

model), or a list of Wald results for a list of tests.

Raises:

Type Description
ArgumentError

there is no implementation for the class of model. An argument the implementation does not have is a TypeError from Python, as for any function.

anova_rma_uni

anova_rma_uni(
    model: RMAResult,
    model2: RMAResult | None = None,
    *,
    object2: RMAResult | None = None,
    btt: int | Sequence[int] | str | None = None,
    X: ArrayLike | PairmatSpec | None = None,
    rhs: ArrayLike | float | None = None,
    adjust: bool | str | None = None,
    refit: bool = False,
    L: ArrayLike | None = None,
    fixed: bool = False,
    test: str | None = None,
    df: int | None = None,
    verbose: bool = False,
    abbrev: bool = False,
    digits: int | Mapping[str, int] | None = None,
    att: Any = None,
    Z: Any = None,
) -> WaldResult | LRTResult | ListAnovaResult

Test coefficients of one rma_uni model, or compare two nested models (metafor's anova.rma).

anova(res, btt=...) tests a subset of coefficients, anova(res, X=L) tests linear combinations L beta = rhs and anova(full, reduced) gives a likelihood-ratio test.

For a model made robust with club_sandwich=True the omnibus test is the cluster-robust Wald test with the small-sample approximation chosen by wald_test of robust (HTZ by default: an F test with df1 and df2 from clubSandwich::Wald_test), and the tests of linear combinations use the degrees of freedom of coef_test. As in R, rhs cannot be used with X for such a model (a warning is given and zero is used).

R source: https://github.com/wviechtb/metafor/blob/master/R/anova.rma.r

Parameters:

Name Type Description Default
model RMAResult

Model fitted by rma_uni.

required
model2 RMAResult | None

A second, nested model fitted to the same data, of the same class, for a likelihood-ratio test. The model with more parameters is the full model; when df is given, model is the full model. Default: none, which gives a Wald test of the coefficients of model.

None
object2 RMAResult | None

R's name for model2; giving both with different values raises InputError.

None
btt int | Sequence[int] | str | None

Coefficients to test jointly: 0-based indices (sorted and without duplicates; an index outside the model raises InputError), a string matched with re.search against the coefficient names (see fixed; metafor uses grep), or a list of several strings or index lists for one test each (a list result, named by the specifications). Default: the coefficients tested by the omnibus test of the model, all but the intercept if there is one.

None
X ArrayLike | PairmatSpec | None

Linear combinations of the coefficients to test: a 1-d array (one combination) or a 2-d array with one row per combination, with all p columns or without the intercept column (a column of ones is then added). Each row is tested against rhs; the result holds one test per row and, if X has full row rank, the omnibus test of all of them (QM is otherwise NaN). Also accepted: a pairmat specification. Default: none.

None
rhs ArrayLike | float | None

Right-hand side of the hypotheses: a number or one value per combination (or per tested coefficient with btt; a different length raises InputError). Default: 0.

None
adjust bool | str | None

Adjust the p-values for multiple testing, as R's p.adjust: True for 'bonferroni', False for 'none', or one of 'holm', 'hochberg', 'hommel', 'bonferroni', 'BH', 'BY', 'fdr' and 'none' (a unique prefix is accepted). It applies to the p-values of the individual tests of the linear combinations, and to the omnibus p-value of a test of moderators (across the elements for a list btt). Default: no adjustment.

None
refit bool

For a likelihood-ratio test of REML models whose fixed effects differ, refit them with ML first (otherwise a warning is given).

False
L ArrayLike | None

Old spelling of X; if both are given, L is used.

None
fixed bool

Match a string btt as a literal substring of the coefficient names instead of as a regular expression.

False
test str | None

With model2: 'LRT' (default) for the likelihood-ratio test, or 'Wald' to test the coefficients that only the full model has, with the Wald test of that model (the models must use the same method). A unique prefix is accepted; anything else raises ArgumentError.

None
df int | None

With model2: the degrees of freedom of the likelihood-ratio test, instead of the difference in the number of parameters (it is also added to the number of parameters of the full model).

None
verbose bool

Add the reason to the error of a cluster-robust test that fails.

False
abbrev bool

Remove factor( and ) from the text of the hypotheses of a test of linear combinations (not described on metafor's reference page, but accepted by its source).

False
digits int | Mapping[str, int] | None

Number of decimals of the printout of the result (also used for the hypotheses of a test of linear combinations), or a mapping as for predict. Default: the digits option, else that of the model.

None
att Any

For location-scale models only; giving it here raises InputError.

None
Z Any

For location-scale models only; giving it here raises InputError.

None

Returns:

Type Description
WaldResult | LRTResult | ListAnovaResult

For a Wald test, a WaldResult with the omnibus statistic QM, its degrees of freedom QMdf and p-value QMp and,

WaldResult | LRTResult | ListAnovaResult

for linear combinations, the estimates Xb, se, zval, pval and the hypotheses hyp. For two models, an

WaldResult | LRTResult | ListAnovaResult

LRTResult (or, with test='Wald', a WaldResult). For a list btt, a ListAnovaResult (a list of Wald results).

Raises:

Type Description
InputError

an argument or the data is invalid (for example att or Z is given, X has the wrong number of columns, btt selects nothing, adjust is unknown, the models differ in class or data or in the number of parameters, or a cluster-robust test cannot be computed).

ArgumentError

test is neither 'LRT' nor 'Wald'.

InternalError

an internal invariant does not hold.

Metafor reference

anova.rma

anova_rma_mv

anova_rma_mv(
    model: RMAMVResult,
    model2: RMAMVResult | None = None,
    *,
    object2: RMAMVResult | None = None,
    btt: int | Sequence[int] | str | None = None,
    X: ArrayLike | PairmatSpec | None = None,
    rhs: ArrayLike | float | None = None,
    adjust: bool | str | None = None,
    refit: bool = False,
    L: ArrayLike | None = None,
    fixed: bool = False,
    test: str | None = None,
    df: int | None = None,
    verbose: bool = False,
    abbrev: bool = False,
    digits: int | Mapping[str, int] | None = None,
    att: Any = None,
    Z: Any = None,
) -> WaldResult | MVLRTResult | ListAnovaResult

Test coefficients of one rma_mv model, or compare two nested models by a likelihood-ratio test (metafor's anova.rma).

The arguments and the handling of club_sandwich=True fits are those of anova_rma_uni; the ML refit repeats the recorded call of the fit with method='ML' (and raises InputError if no call was recorded). Only the observed outcomes (not the sampling variances) are compared for equality in a likelihood-ratio test.

R source: https://github.com/wviechtb/metafor/blob/master/R/anova.rma.r

Parameters:

Name Type Description Default
model RMAMVResult

Model fitted by rma_mv.

required
model2 RMAMVResult | None

A second, nested model fitted to the same data, of the same class, for a likelihood-ratio test. The model with more parameters is the full model; when df is given, model is the full model. Default: none, which gives a Wald test of the coefficients of model.

None
object2 RMAMVResult | None

R's name for model2; giving both with different values raises InputError.

None
btt int | Sequence[int] | str | None

Coefficients to test jointly: 0-based indices (sorted and without duplicates; an index outside the model raises InputError), a string matched with re.search against the coefficient names (see fixed; metafor uses grep), or a list of several strings or index lists for one test each (a list result, named by the specifications). Default: the coefficients tested by the omnibus test of the model, all but the intercept if there is one.

None
X ArrayLike | PairmatSpec | None

Linear combinations of the coefficients to test: a 1-d array (one combination) or a 2-d array with one row per combination, with all p columns or without the intercept column (a column of ones is then added). Each row is tested against rhs; the result holds one test per row and, if X has full row rank, the omnibus test of all of them (QM is otherwise NaN). Also accepted: a pairmat specification. Default: none.

None
rhs ArrayLike | float | None

Right-hand side of the hypotheses: a number or one value per combination (or per tested coefficient with btt; a different length raises InputError). Default: 0.

None
adjust bool | str | None

Adjust the p-values for multiple testing, as R's p.adjust: True for 'bonferroni', False for 'none', or one of 'holm', 'hochberg', 'hommel', 'bonferroni', 'BH', 'BY', 'fdr' and 'none' (a unique prefix is accepted). It applies to the p-values of the individual tests of the linear combinations, and to the omnibus p-value of a test of moderators (across the elements for a list btt). Default: no adjustment.

None
refit bool

For a likelihood-ratio test of REML models whose fixed effects differ, refit them with ML first (otherwise a warning is given).

False
L ArrayLike | None

Old spelling of X; if both are given, L is used.

None
fixed bool

Match a string btt as a literal substring of the coefficient names instead of as a regular expression.

False
test str | None

With model2: 'LRT' (default) for the likelihood-ratio test, or 'Wald' to test the coefficients that only the full model has, with the Wald test of that model (the models must use the same method). A unique prefix is accepted; anything else raises ArgumentError.

None
df int | None

With model2: the degrees of freedom of the likelihood-ratio test, instead of the difference in the number of parameters (it is also added to the number of parameters of the full model).

None
verbose bool

Add the reason to the error of a cluster-robust test that fails.

False
abbrev bool

Remove factor( and ) from the text of the hypotheses of a test of linear combinations (not described on metafor's reference page, but accepted by its source).

False
digits int | Mapping[str, int] | None

Number of decimals of the printout of the result (also used for the hypotheses of a test of linear combinations), or a mapping as for predict. Default: the digits option, else that of the model.

None
att Any

For location-scale models only; giving it here raises InputError.

None
Z Any

For location-scale models only; giving it here raises InputError.

None

Returns:

Type Description
WaldResult | MVLRTResult | ListAnovaResult

For a Wald test, a WaldResult; for two models, an MVLRTResult with the fields df_full, df_reduced, LRT,

WaldResult | MVLRTResult | ListAnovaResult

pval, fit_stats_full, fit_stats_reduced, QE_full, QE_reduced, digits and method of LRTResult

WaldResult | MVLRTResult | ListAnovaResult

(its tau2_f, tau2_r and R2 are NaN, as metafor stores NA); with test='Wald', a WaldResult; for a list btt, a

WaldResult | MVLRTResult | ListAnovaResult

ListAnovaResult (a list of Wald results).

Raises:

Type Description
InputError

an argument or the data is invalid (for example att or Z is given, X has the wrong number of columns, btt selects nothing, adjust is unknown, the models differ in class, data or number of parameters, an ML refit fails, or a cluster-robust test cannot be computed).

ArgumentError

test is neither 'LRT' nor 'Wald'.

InternalError

the cluster-robust fit has lost its variance estimator.

Metafor reference

anova.rma

anova_rma_ls

anova_rma_ls(
    model: RMALSResult,
    model2: RMALSResult | None = None,
    *,
    object2: RMALSResult | None = None,
    btt: int | Sequence[int] | str | None = None,
    X: ArrayLike | PairmatSpec | None = None,
    att: int
    | Sequence[int]
    | str
    | None
    | Sequence[Any] = None,
    Z: ArrayLike | None = None,
    rhs: ArrayLike | float | None = None,
    adjust: bool | str | None = None,
    digits: int | Mapping[str, int] | None = None,
    refit: bool = False,
    abbrev: bool = False,
    L: ArrayLike | None = None,
    fixed: bool = False,
    test: str | None = None,
    df: int | None = None,
    verbose: bool = False,
) -> LSWaldResult | MVLRTResult | list[LSWaldResult]

Wald tests of the location and scale coefficients of a location-scale model or, given a second model, a likelihood-ratio test (metafor's anova.rma).

R source: https://github.com/wviechtb/metafor/blob/master/R/anova.rma.r

Parameters:

Name Type Description Default
model RMALSResult

Location-scale model fitted by rma_uni with scale.

required
model2 RMALSResult | None

A second, nested location-scale model fitted to the same data for a likelihood-ratio test. The model with more parameters is the full model; when df is given, model is the full model. Default: none, which gives a Wald test of the coefficients of model.

None
object2 RMALSResult | None

R's name for model2; giving both with different values raises InputError.

None
btt int | Sequence[int] | str | None

Location coefficients to test jointly: 0-based indices (sorted and without duplicates) or a string matched with re.search against the coefficient names (see fixed; metafor uses grep). A list of several tests is not supported here. Default: the coefficients tested by the omnibus test of the model, all but the intercept if there is one. Cannot be combined with att.

None
X ArrayLike | PairmatSpec | None

Linear combinations of the location coefficients to test, as for anova_rma_uni. Cannot be combined with Z.

None
att int | Sequence[int] | str | None | Sequence[Any]

Scale coefficients to test jointly: 0-based indices or a string matched against the coefficient names of the scale model, or a list of index lists ([[0], [1]]), which returns a list of tests (rhs cannot be used with a list).

None
Z ArrayLike | None

Linear combinations of the scale coefficients to test (a 1-d or 2-d array, with all q columns or without the intercept column, tested against rhs).

None
rhs ArrayLike | float | None

Right-hand side of the hypotheses of X and Z (and of the tests of btt and att): a number or one value per combination or coefficient (a different length raises InputError). Default: 0.

None
adjust bool | str | None

Adjust the p-values of the individual tests (X, Z) or of a list of tests (att) for multiple testing, as R's p.adjust: True for 'bonferroni', False for 'none', or one of 'holm', 'hochberg', 'hommel', 'bonferroni', 'BH', 'BY', 'fdr' and 'none' (a unique prefix is accepted). Default: no adjustment.

None
digits int | Mapping[str, int] | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
refit bool

With model2, refit REML fits with ML when their location models differ (otherwise a warning is given).

False
abbrev bool

Remove factor( and ) from the text of the hypotheses of X and Z.

False
L ArrayLike | None

Old spelling of X; if both are given, L is used.

None
fixed bool

Match a string btt or att as a literal substring of the coefficient names instead of as a regular expression.

False
test str | None

With model2: 'LRT' (default) for the likelihood-ratio test, or 'Wald' to test the location coefficients that only the full model has, with the Wald test of that model (the models must use the same method). A unique prefix is accepted; anything else raises ArgumentError.

None
df int | None

With model2: the degrees of freedom of the likelihood-ratio test, instead of the difference in the number of parameters (it is also added to the number of parameters of the full model).

None
verbose bool

Accepted for metafor's cluster-robust tests, which location-scale models do not have; it has no effect.

False

Returns:

Type Description
LSWaldResult | MVLRTResult | list[LSWaldResult]

A Wald test result, an LSWaldResult: for location coefficients (btt, X) the statistic is in QM, QMdf and QMp, for scale

LSWaldResult | MVLRTResult | list[LSWaldResult]

coefficients (att, Z) in QS, QSdf and QSp (the other statistic is NaN); stat, df and pval_omnibus give whichever

LSWaldResult | MVLRTResult | list[LSWaldResult]

applies, and tests of linear combinations also hold hyp, estimate, se, zval, pval and ddf. A list of them for a list

LSWaldResult | MVLRTResult | list[LSWaldResult]

att. With model2, a likelihood-ratio test result, an MVLRTResult (fields df_full, df_reduced, LRT, pval,

LSWaldResult | MVLRTResult | list[LSWaldResult]

fit_stats_full, fit_stats_reduced, QE_full, QE_reduced and method), or an LSWaldResult with test='Wald'.

Raises:

Type Description
InputError

an argument is invalid (for example both X and Z or both btt and att, rhs of the wrong length or with a list att, X or Z with the wrong number of columns, btt or att selecting nothing, an unknown adjust, or models that differ in class, data or number of parameters or cannot be compared).

ArgumentError

test is neither 'LRT' nor 'Wald'.

Metafor reference

anova.rma

WaldResult dataclass

WaldResult(
    QM: float,
    QMdf: tuple[int, float | None],
    QMp: float,
    btt: tuple[int, ...] | None = None,
    Xb: FloatArray | None = None,
    se: FloatArray | None = None,
    zval: FloatArray | None = None,
    pval: FloatArray | None = None,
    ddf: FloatArray | None = None,
    hyp: tuple[str, ...] | None = None,
    digits: int = 4,
    k: int | None = None,
    p: int | None = None,
    test: str | None = None,
    class_: tuple[str, ...] | None = None,
)

Bases: HtmlRepr

Omnibus Wald test (QM) and, for linear combinations, individual tests, as returned by anova (metafor's anova.rma object).

Attributes:

Name Type Description
QM float

Test statistic of the omnibus test: the chi-square statistic, or the F statistic (the chi-square statistic divided by m) when the degrees of freedom of the denominator are known. NaN when the test cannot be computed (X not of full row rank, singular covariance matrix).

QMdf tuple[int, float | None]

Degrees of freedom of the omnibus test: (m, None) for a chi-square test, (m, ddf) for an F test.

QMp float

p-value of the omnibus test (adjusted if adjust was given for a test of moderators).

btt tuple[int, ...] | None

Tested coefficients (0-based, sorted) of a test of moderators; None for a test of linear combinations.

Xb FloatArray | None

Estimates of the linear combinations (less rhs); None for a test of moderators.

se FloatArray | None

Standard errors of the combinations.

zval FloatArray | None

Test statistics of the combinations (t values when ddf is not None).

pval FloatArray | None

p-values of the combinations (adjusted if requested).

ddf FloatArray | None

Degrees of freedom of the t tests of the combinations (one per combination), None for z tests.

hyp tuple[str, ...] | None

Hypotheses as R prints them (for example 'intrcpt + 30*ablat = 0').

digits int

Number of decimals of the printout.

k int | None

Number of studies of the model (None if not filled in).

p int | None

Number of coefficients of the model.

test str | None

The test of the model's coefficients, 'z', 't', 'knha' or 'adhoc'.

class_ tuple[str, ...] | None

The class vector of the model a test of moderators was made for (metafor's class), for example ('rma.uni', 'rma').

class_ class-attribute instance-attribute

class_: tuple[str, ...] | None = None

The class vector of the model a test of moderators was made for (the class element of metafor's result), e.g. ('rma.uni', 'rma').

m property

m: int

The number of coefficients or linear combinations tested, metafor's m.

type property

type: str

The kind of test, 'Wald.btt' (coefficients) or 'Wald.Xb' (linear combinations), metafor's type.

to_frame

to_frame() -> DataFrame

The test as a data frame (metafor's as.data.frame.anova.rma).

A test of moderators gives one row with the columns coefs, QM, df and pval (Fval, df1, df2 and pval for F tests); tests of linear combinations give one row per hypothesis (row names '1:', '2:', ...) with hyp, estimate, se, zval (tval and df for t tests) and pval.

summary

summary(
    digits: int | Mapping[str, int] | None = None,
    *,
    signif_stars: bool | None = None,
) -> str

The printout of metafor's print.anova.rma; digits defaults to the digits option, else to that of the test.

LRTResult dataclass

LRTResult(
    df_full: int,
    df_reduced: int,
    LRT: float,
    pval: float,
    fit_stats_full: tuple[
        float, float, float, float, float
    ],
    fit_stats_reduced: tuple[
        float, float, float, float, float
    ],
    QE_full: float,
    QE_reduced: float,
    tau2_full: float,
    tau2_reduced: float,
    R2: float,
    digits: int = 4,
    method: str | None = None,
    class_f: tuple[str, ...] | None = None,
)

Bases: HtmlRepr

Likelihood-ratio test of a full against a reduced model, as returned by anova for two models.

Attributes:

Name Type Description
df_full int

Number of parameters of the full model (plus df if that was given).

df_reduced int

Number of parameters of the reduced model.

LRT float

Likelihood-ratio test statistic.

pval float

p-value of the test.

fit_stats_full tuple[float, float, float, float, float]

Fit statistics of the full model (log-likelihood, deviance, AIC, BIC, AICc), from the REML likelihood if the models were fitted with REML and the ML likelihood otherwise.

fit_stats_reduced tuple[float, float, float, float, float]

Fit statistics of the reduced model, in the same order.

QE_full float

Test statistic for residual heterogeneity of the full model.

QE_reduced float

Test statistic for residual heterogeneity of the reduced model.

tau2_full float

Estimate of tau^2 of the full model.

tau2_reduced float

Estimate of tau^2 of the reduced model.

R2 float

Percentage reduction in tau^2 (or in the residual variance for fixed-effects models) from the reduced to the full model; 0 if tau^2 of the reduced model is 0.

digits int

Number of decimals of the printout.

method str | None

Estimation method of the full model.

class_f tuple[str, ...] | None

Class vector of the full model (metafor's class.f).

class_f class-attribute instance-attribute

class_f: tuple[str, ...] | None = None

The class vector of the full model (metafor's class.f).

type property

type: str

The kind of test, 'LRT' (metafor's type).

fit_stats_f property

fit_stats_f: tuple[float, float, float, float, float]

The fit statistics of the full model, metafor's fit.stats.f.

fit_stats_r property

fit_stats_r: tuple[float, float, float, float, float]

The fit statistics of the reduced model, metafor's fit.stats.r.

parms_f property

parms_f: int

The number of parameters of the full model, metafor's parms.f.

parms_r property

parms_r: int

The number of parameters of the reduced model, metafor's parms.r.

QE_f property

QE_f: float

The test statistic for residual heterogeneity of the full model, metafor's QE.f.

QE_r property

QE_r: float

The test statistic for residual heterogeneity of the reduced model, metafor's QE.r.

tau2_f property

tau2_f: float

The amount of heterogeneity of the full model, metafor's tau2.f.

tau2_r property

tau2_r: float

The amount of heterogeneity of the reduced model, metafor's tau2.r.

hettest

hettest(
    x: RMAResult
    | RMAMVResult
    | FixedBinaryResult
    | RMALSResult
    | SelmodelResult
    | GLMMResult
    | ArrayLike
    | str,
    vi: ArrayLike | str | None = None,
    *,
    sei: ArrayLike | str | None = None,
    subset: ArrayLike | None = None,
    data: DataFrame | None = None,
    method: str | None = None,
    test: str | Sequence[str] = 'score',
    boot: bool | int | Sequence[bool] = True,
    progbar: bool = False,
    digits: int | None = None,
    control: Mapping[str, Any] | None = None,
    seed: int | None = None,
    mom: bool = False,
    model: RMAResult | None = None,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    verbose: bool = False,
) -> HettestResult

Test for heteroscedastic heterogeneity in a random-effects model (metafor's hettest).

The standard random-effects model assumes that the heterogeneity of the true effects is homoscedastic; this tests that assumption against study-specific tau^2_i values, with a likelihood-ratio, Wald-type or score test, or with goodness-of-fit tests of the Pearson residuals. P-values come from a parametric bootstrap, the first sample being the data. Without seed the bootstrap uses the generator of set_seed.

Parameters:

Name Type Description Default
x RMAResult | RMAMVResult | FixedBinaryResult | RMALSResult | SelmodelResult | GLMMResult | ArrayLike | str

Effect size estimates (an array, or a column name of data), or a random-effects model without moderators (rma_uni), normally fitted by ML or REML. For a model fitted with another method a warning is given and the test is based on method. Models with moderators and other classes of model raise an error.

required
vi ArrayLike | str | None

Sampling variances (array or column name). Ignored (with a warning) if x is a model.

None
sei ArrayLike | str | None

Standard errors, instead of vi (array or column name). Ignored (with a warning) if x is a model.

None
subset ArrayLike | None

Which studies to use: a boolean array or 0-based indices. Ignored (with a warning) if x is a model.

None
data DataFrame | None

Data frame holding the variables named in x, vi and sei.

None
method str | None

'REML' (default) or 'ML' (case-sensitive; anything else raises InputError). Ignored (with a warning) if x is a model fitted by ML or REML, whose own method is used.

None
test str | Sequence[str]

One test or a sequence of tests (case insensitive): 'score' (default), 'lrt' (likelihood ratio), 'wald', or the goodness-of-fit tests of the Pearson residuals 'ksn', 'ksx2', 'adn' and 'adx2' (Kolmogorov-Smirnov and Anderson-Darling tests of normality and of the chi-square distribution of the squared residuals). The goodness-of-fit tests always bootstrap.

'score'
boot bool | int | Sequence[bool]

True bootstraps with 1000 samples, a number sets the number of samples (and bootstraps every test), False uses the chi-square approximation with k - 1 degrees of freedom. May be a sequence of bools, one per test (or one for all). The goodness-of-fit tests always bootstrap.

True
progbar bool

Print a progress bar to stderr during the bootstrap. Unlike metafor, off by default.

False
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model x (4 for a vector).

None
control Mapping[str, Any] | None

Mapping of control values (names written with . or _): tau2i_init (starting values of the tau^2_i: one value or one per study, not negative; default: the tau^2 of the null model, but at least 0.01), threshold (convergence threshold, 1e-8) and maxiter (1000). Not used if x is a model, as in metafor. Names must be given in full (metafor accepts partial names).

None
seed int | None

Seed for the bootstrap: it re-seeds the generator of set_seed, as set.seed(seed) does in R, before the samples are drawn. Default: continue with that generator.

None
mom bool

Estimate the tau^2_i by the method of moments (max(0, e_i^2 / (1 - h_i) - v_i)).

False
model RMAResult | None

For a vector x: an intercept-only model already fitted to the same data, used as the null model instead of fitting it again (metafor's undocumented argument).

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

As R's na.action: studies with missing values in a vector x are omitted with a warning ('omit', 'exclude' and 'pass' act alike), except for 'fail', which raises. No effect for a fitted model.

'omit'
verbose bool

Read by metafor but without effect there as well; no effect here.

False

Returns:

Type Description
HettestResult

A HettestResult with one entry per requested test in statistic, df, pval, test and boot, plus

HettestResult

tau2i, se_tau2i (Wald-type test) and the bootstrapped statistics statistic_boot.

Raises:

Type Description
ArgumentError

x is not a fitted model.

InputError

an argument or the data is invalid (unknown test, method or control entry, wrong length of boot or tau2i_init, k <= 1, a model with moderators), the null model or the tau^2_i could not be estimated, or studies are missing and na_action='fail'.

NotSupportedError

x is a model of a class the test is not available for.

Metafor reference

hettest

HettestResult dataclass

HettestResult(
    statistic: FloatArray,
    df: FloatArray,
    pval: FloatArray,
    method: str,
    test: tuple[str, ...],
    boot: tuple[bool, ...],
    iter: int,
    digits: int,
    tau2i: FloatArray | None,
    se_tau2i: FloatArray | None = None,
    statistic_boot: FloatArray | None = None,
)

Result of hettest. summary() gives the printout of metafor's print.hettest.

Attributes:

Name Type Description
statistic FloatArray

Test statistic, one per requested test.

df FloatArray

Degrees of freedom, one per test (k - 1 for the likelihood-ratio, Wald-type and score tests, NaN for goodness-of-fit tests).

pval FloatArray

p-value, one per test (bootstrap p-value for the tests that used the bootstrap, else from the chi-square distribution).

method str

Estimation method the tests are based on, 'ML' or 'REML'.

test tuple[str, ...]

The requested tests, in lower case.

boot tuple[bool, ...]

Whether each test used the bootstrap (always True for the goodness-of-fit tests).

iter int

Number of bootstrap samples (1000 unless boot was a number).

digits int

Number of decimals of the printout.

tau2i FloatArray | None

Estimated study-specific heterogeneity variances of the saturated model, one per study (None if the iterations did not converge and no test needed them).

se_tau2i FloatArray | None

Standard errors of tau2i (only with the Wald-type test, else None).

statistic_boot FloatArray | None

Bootstrapped statistics, an array with one row per sample and one column per test (None if no test used the bootstrap; NaN for samples that failed, and for the tests that did not use the bootstrap). The first sample is the data itself.

permutest

permutest(
    x: Any, *args: Any, **kwargs: Any
) -> (
    PermutestResult
    | int
    | float
    | LSPermutestResult
    | list[float]
)

Permutation tests for the coefficients of a fitted model (metafor's permutest).

This is a single-dispatch function: the implementation is chosen by the class of x. See permutest_rma_uni and permutest_rma_ls.

Parameters:

Name Type Description Default
x Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation (exact, iter, ...).

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
PermutestResult | int | float | LSPermutestResult | list[float]

A PermutestResult (a location-scale result for a location-scale model); with exact='i' the number of iterations an

PermutestResult | int | float | LSPermutestResult | list[float]

exact test needs.

Raises:

Type Description
ArgumentError

there is no implementation for the class of x.

TypeError

the implementation does not accept a keyword argument.

permutest_rma_uni

permutest_rma_uni(
    x: RMAResult,
    exact: bool | Literal['i'] = False,
    iter: int = 1000,
    btt: int | Sequence[int] | str | None = None,
    permci: bool | Sequence[int] = False,
    digits: int | None = None,
    control: Mapping[str, Any] | None = None,
    *,
    seed: int | None = None,
    tol: float | None = None,
    fixed: bool = False,
    progbar: bool = False,
    verbose: bool = False,
) -> PermutestResult | int | float

Permutation test for an rma_uni fit (metafor's permutest.rma.uni).

For a model without moderators the signs of the estimates are permuted, otherwise the rows of the model matrix. The p-value is the proportion of permutations whose statistic is as extreme as the observed one (the first permutation of an approximate test is the data, which avoids p-values of 0). With few studies the smallest possible p-value can exceed 0.05.

R source: https://github.com/wviechtb/metafor/blob/master/R/permutest.rma.uni.r

Parameters:

Name Type Description Default
x RMAResult

Model fitted by rma_uni (not a robust result).

required
exact bool | Literal['i']

True carries out an exact test (all unique permutations; also used if iter exceeds their number); 'i' returns the number of iterations an exact test needs; False (default) uses iter random permutations.

False
iter int

Number of random permutations for an approximate test (at least 2).

1000
btt int | Sequence[int] | str | None

Coefficients the omnibus test refers to: 0-based indices or a string searched for (Python re.search) in the coefficient names. Default: that of the model.

None
permci bool | Sequence[int]

True, or 0-based coefficient indices, to also find permutation-based confidence interval bounds (slow). A bound that cannot be found is NaN.

False
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
control Mapping[str, Any] | None

Mapping with metafor's control values: comptol (tolerance of the comparisons), tol and maxiter (root finding for permci), alternative ('two.sided', 'less' or 'greater'), p2defn ('abs' or 'px2'), stat ('test' or 'coef'), cialt (alternative for the CI bounds) and distfac (factor widening the search interval for the CI bounds).

None
seed int | None

Seed of the random permutations. Default: drawn from the R-compatible generator of set_seed, which is left in the state the permutations ended in, as R's global generator is.

None
tol float | None

Old spelling of the comptol entry of control.

None
fixed bool

Match a string btt literally instead of as a regular expression.

False
progbar bool

Print a progress bar to stderr while the permutations are run (default False; metafor's default is TRUE).

False
verbose bool

Accepted and ignored (metafor shows the errors of refits that fail during the permutations).

False

Returns:

Type Description
PermutestResult | int | float

A PermutestResult with the coefficient table (beta, se, zval, pval, ci_lb, ci_ub), the omnibus

PermutestResult | int | float

test (QM, QMp) and the permutation distributions. With exact='i', the number of iterations an exact test needs.

Raises:

Type Description
InputError

iter is below 2; btt or permci names a coefficient that does not exist; a control entry is not accepted; an exact test needs more iterations than the largest float, or more than can be allocated (R stops with an error as well).

ArgumentError

control has an unknown entry.

NotSupportedError

x is a robust result.

Metafor reference

permutest

permutest_rma_ls

permutest_rma_ls(
    x: RMALSResult,
    exact: bool | Literal['i'] = False,
    iter: int = 1000,
    btt: int | Sequence[int] | str | None = None,
    att: int | Sequence[int] | str | None = None,
    digits: int | None = None,
    control: Mapping[str, Any] | None = None,
    *,
    seed: int | None = None,
    tol: float | None = None,
    skip_beta: bool = False,
    skip_alpha: bool = False,
    progbar: bool = False,
    permci: bool = False,
    fixed: bool = False,
    verbose: bool = False,
) -> LSPermutestResult | list[float]

Permutation tests for the location and scale coefficients of a location-scale fit (metafor's permutest.rma.ls).

For the scale part with control={'p2defn': 'px2'}, the current metafor source (permutest.rma.ls.r) refers to x$zval.alpha.[j], which does not exist, so the p-values there are NaN in R; here they are computed from the observed test statistics. An intercept-only scale model skips the scale part with a warning.

R source: https://github.com/wviechtb/metafor/blob/master/R/permutest.rma.ls.r

Parameters:

Name Type Description Default
x RMALSResult

Location-scale model fitted by rma_uni with scale.

required
exact bool | Literal['i']

True carries out an exact test of each part (all unique permutations); 'i' returns the numbers of iterations an exact test needs for the location and the scale part; False (default) uses iter random permutations.

False
iter int

Number of random permutations for an approximate test (at least 2).

1000
btt int | Sequence[int] | str | None

Location coefficients the omnibus test refers to: 0-based indices or a string searched for (Python re.search) in the coefficient names. Default: that of the model.

None
att int | Sequence[int] | str | None

Scale coefficients the omnibus test refers to: 0-based indices or a string searched for (Python re.search) in the scale coefficient names. Default: that of the model.

None
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
control Mapping[str, Any] | None

Mapping with comptol, alternative, p2defn and stat, as for permutest.

None
seed int | None

Seed of the generator for each approximate part. Default: drawn from the generator of set_seed.

None
tol float | None

Old spelling of the comptol entry of control.

None
skip_beta bool

Skip the permutation test of the location part.

False
skip_alpha bool

Skip the permutation test of the scale part.

False
progbar bool

Print a progress bar to stderr for each part (default False; metafor's default is TRUE).

False
permci bool

Only warns, as permutation-based confidence intervals are not available for location-scale models in metafor either.

False
fixed bool

Match a string btt or att literally instead of as a regular expression.

False
verbose bool

Accepted and ignored (metafor shows the errors of refits that fail during the permutations).

False

Returns:

Type Description
LSPermutestResult | list[float]

A result (an LSPermutestResult) with the permutation tests of the location part and of the scale part. With exact='i', a list with the

LSPermutestResult | list[float]

numbers of iterations an exact test needs.

Raises:

Type Description
InputError

iter is below 2; skip_beta and skip_alpha are both set (or the scale model has only an intercept and skip_beta is set); btt or att matches no coefficient; a control entry is not accepted; an exact test needs more iterations than can be allocated (R stops with an error as well).

ArgumentError

control has an unknown entry.

Metafor reference

permutest

PermutestResult dataclass

PermutestResult(
    pval: FloatArray,
    QMdf: tuple[int, int | None],
    QMp: float,
    beta: FloatArray,
    se: FloatArray,
    zval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    QM: float,
    k: int,
    p: int,
    btt: tuple[int, ...],
    m: int,
    test: str,
    ddf: int | None,
    int_only: bool,
    int_incl: bool,
    coef_names: tuple[str, ...],
    exact_iter: int | float,
    permci: bool,
    alternative: str,
    p2defn: str,
    stat: str,
    QM_perm: FloatArray,
    zval_perm: DataFrame,
    beta_perm: DataFrame,
    digits: int = 4,
)

Bases: HtmlRepr

Permutation-based p-values (and optionally CI bounds) for the coefficients of a model, as returned by permutest. to_frame() and coef() give the coefficient table and summary() the printout.

Attributes:

Name Type Description
pval FloatArray

Permutation p-values of the coefficients.

QMdf tuple[int, int | None]

Degrees of freedom of the omnibus test, (m, None) for the z test and (m, ddf) for the t test.

QMp float

Permutation p-value of the omnibus test.

beta FloatArray

Estimates of the coefficients.

se FloatArray

Standard errors of the coefficients.

zval FloatArray

Test statistics of the coefficients.

ci_lb FloatArray

Lower confidence interval bounds (permutation-based with permci, else the usual ones).

ci_ub FloatArray

Upper confidence interval bounds.

QM float

Test statistic of the omnibus test.

k int

Number of studies.

p int

Number of coefficients.

btt tuple[int, ...]

Coefficients (0-based) the omnibus test refers to.

m int

Number of coefficients in the omnibus test.

test str

Test used by the model: 'z', 't', 'knha' or 'adhoc'.

ddf int | None

Residual degrees of freedom of the t test, or None for the z test.

int_only bool

Whether the model has only an intercept.

int_incl bool

Whether the model has an intercept.

coef_names tuple[str, ...]

Names of the coefficients.

exact_iter int | float

Number of iterations an exact test needs (inf if it exceeds the largest float).

permci bool

Whether permutation-based CI bounds were computed (False if permci was requested but the number of permutations is too low for the confidence level).

alternative str

Alternative hypothesis of the test (the alternative control entry; with permutation-based CI bounds, the one of the last bound search, as in metafor).

p2defn str

Definition of the two-sided p-value.

stat str

Statistic used for the coefficients.

QM_perm FloatArray

Omnibus statistics of every permutation (for the approximate test the first one is the observed one, as in metafor).

zval_perm DataFrame

Test statistics of every permutation, one column per coefficient.

beta_perm DataFrame

Estimates of every permutation, one column per coefficient.

digits int

Number of decimals of the printout.

dfs property

dfs: int | None

R's dfs: the residual degrees of freedom (ddf) of the test.

skip_beta property

skip_beta: bool

R's skip.beta: the plain model never skips the coefficients.

coef

coef() -> DataFrame

The table of the coefficients with the permutation p-values (estimate, se, zval, pval, ci.lb, ci.ub), as metafor's coef.permutest.rma.uni (tval and df for the t-test).

summary

summary(
    digits: int | None = None,
    *,
    signif_stars: bool | None = None,
    signif_legend: bool | None = None,
    num: bool = False,
) -> str

The printout of print(x, digits=, signif.stars=, signif.legend=, num=): digits default to those of the fit; num numbers the rows of the coefficient table.

profile

profile(
    fitted: Any, *args: Any, **kwargs: Any
) -> ProfileResult

Profile likelihood of a variance component of a fitted model (metafor's profile).

This is a single-dispatch function: the implementation is chosen by the class of fitted. See profile_rma_uni, profile_rma_ls, profile_rma_mv; selection models (selmodel) are also supported.

Parameters:

Name Type Description Default
fitted Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation.

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
ProfileResult

The profile: a ProfileResult for an rma_uni fit, an LSProfileResult for a location-scale fit,

ProfileResult

a MVProfileResult for an rma_mv fit and a

ProfileResult

SelProfileResult for a selection model; a list of them (a ProfileList) when several components are profiled.

Raises:

Type Description
ArgumentError

there is no implementation for the class of fitted.

InputError

raised by the implementation for an invalid argument.

profile_rma_uni

profile_rma_uni(
    fitted: RMAResult,
    xlim: Sequence[float] | None = None,
    ylim: Sequence[float] | None = None,
    steps: int | ArrayLike = 20,
    lltol: float = 0.001,
    plot: bool = False,
    *,
    sqrt: bool = False,
    exp: bool = False,
    ax: Any = None,
    progbar: bool = False,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    pred: bool = False,
    blup: bool = False,
    newmods: ArrayLike
    | Mapping[str, float]
    | Series
    | DataFrame
    | None = None,
    LB: bool = False,
    **plot_args: Any,
) -> ProfileResult

Profile the likelihood of an rma_uni fit over tau^2 (metafor's profile.rma.uni).

The model is refitted with tau^2 fixed at each value of a grid and the log-likelihood (and the coefficients) recorded. xlim defaults to the range spanned by the Q-profile CI for tau^2 and the estimate (the upper end at least 0.1). Models with equal or fixed effects cannot be profiled.

R source: https://github.com/wviechtb/metafor/blob/master/R/profile.rma.uni.r

Parameters:

Name Type Description Default
fitted RMAResult

Random- or mixed-effects model fitted by rma_uni (not an equal- or fixed-effects model).

required
xlim Sequence[float] | None

Range (lower, upper) of tau^2 values (tau values with sqrt=True). Default: the range spanned by the Q-profile CI for tau^2 and the estimate.

None
ylim Sequence[float] | None

Range (lower, upper) of the profile log-likelihood stored in the result (and drawn by the plot). Default: the range of the profile and the maximum.

None
steps int | ArrayLike

Number of equally spaced values in xlim to profile over (a single number, at least 2), or a sequence of two or more values to profile at (then xlim defaults to their range). Missing values are not allowed.

20
lltol float

Tolerance when checking whether a profiled log-likelihood exceeds that of the fitted model (a warning is given if it does).

0.001
plot bool

Draw the profile with plot_profile (default False; metafor's default is TRUE).

False
sqrt bool

Profile over tau instead of tau^2 (the grid and xlim are then on the tau scale).

False
exp bool

Report the likelihood instead of the log-likelihood (exponentiate it; ylim is then not widened by 0.1).

False
ax Any

Matplotlib axes to draw on (with plot=True). Default: a new figure.

None
progbar bool

Print a progress bar to stderr while the models of the grid are fitted (default False; metafor's default is TRUE).

False
parallel Literal['no', 'snow', 'multicore']

Parallel fitting of the grid: 'no' (default), 'snow' or 'multicore'; both use a process pool ('multicore' forks the workers where the platform allows). As in metafor, 'no' with ncpus > 1 (or with cl) is 'snow', and 'snow' or 'multicore' with ncpus < 2 and no cl runs serially. The result equals that of the serial run. Any other value raises an InputError.

'no'
ncpus int

Number of worker processes (at least 1).

1
cl Executor | None

Executor to run the fits on instead of creating a process pool of ncpus workers.

None
pred bool

Also store the predicted values of each refit (for newmods, or the fitted values without it, as predict); metafor's undocumented argument.

False
blup bool

Also store the BLUPs (blup) of each refit; metafor's undocumented argument.

False
newmods ArrayLike | Mapping[str, float] | Series | DataFrame | None

Moderator values for the predictions stored with pred=True, as for predict.

None
LB bool

Accepted as in metafor, where it chooses parLapplyLB; it changes no result.

False
**plot_args Any

Further keyword arguments passed on to plot_profile (pch, cline, refline, xlab, ylab, main, log, cex, lwd), as metafor's ... is to plot.profile.rma; they are not used (and not checked) with plot=False.

{}

Returns:

Type Description
ProfileResult

The profile, a ProfileResult with the grid tau2, the log-likelihoods ll, the coefficients and their CI bounds at

ProfileResult

each grid value, and the estimate vc and maximum log-likelihood maxll of the model.

Raises:

Type Description
InputError

the model uses an equal- or fixed-effects method; steps has missing values or is a single number below 2; xlim or ylim does not have length 2; xlim cannot be set automatically; parallel is not one of the accepted values or ncpus is below 1; with pred=True no predictions can be computed.

Metafor reference

profile.rma

profile_rma_ls

profile_rma_ls(
    fitted: RMALSResult,
    alpha: int | None = None,
    xlim: Sequence[float] | None = None,
    ylim: Sequence[float] | None = None,
    steps: int | ArrayLike = 20,
    lltol: float = 0.001,
    *,
    exp: bool = False,
    progbar: bool = False,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    plot: bool = False,
    ax: Axes | None = None,
    sub1: bool = False,
    LB: bool = False,
    **plot_args: Any,
) -> LSProfileResult | list[LSProfileResult]

Profile the likelihood of a location-scale model over a scale coefficient (metafor's profile.rma.ls).

Without alpha every estimated scale coefficient is profiled and a list is returned (a single result if there is one). xlim defaults to the estimate plus and minus 2.576 standard errors, limited by alpha_min and alpha_max of the control settings.

R source: https://github.com/wviechtb/metafor/blob/master/R/profile.rma.ls.r

Parameters:

Name Type Description Default
fitted RMALSResult

Location-scale model fitted by rma_uni with scale.

required
alpha int | None

0-based position of the scale coefficient to profile (0 is the first, usually the intercept; metafor counts from 1). Default: all estimated scale coefficients.

None
xlim Sequence[float] | None

Range (lower, upper) of the profiled values of the coefficient. Default: the estimate +- 2.576 standard errors, limited by the control settings.

None
ylim Sequence[float] | None

Range (lower, upper) of the profile log-likelihood stored in the result (and drawn by the plot). Default: the range of the profile and the maximum.

None
steps int | ArrayLike

Number of equally spaced values in xlim to profile over (a single number, at least 2), or a sequence of two or more values to profile at (then xlim defaults to their range). Missing values are not allowed.

20
lltol float

Tolerance when checking whether a profiled log-likelihood exceeds that of the fitted model (a warning is given if it does).

0.001
exp bool

Report the likelihood instead of the log-likelihood (exponentiate it; ylim is then not widened by 0.1).

False
progbar bool

Print a progress bar to stderr while the models of the grid are fitted (default False; metafor's default is TRUE).

False
parallel Literal['no', 'snow', 'multicore']

Parallel fitting of the grid: 'no' (default), 'snow' or 'multicore'; both use a process pool ('multicore' forks the workers where the platform allows). As in metafor, 'no' with ncpus > 1 (or with cl) is 'snow', and 'snow' or 'multicore' with ncpus < 2 and no cl runs serially. The result equals that of the serial run. Any other value raises an InputError.

'no'
ncpus int

Number of worker processes (at least 1).

1
cl Executor | None

Executor to run the fits on instead of creating a process pool of ncpus workers.

None
plot bool

Draw the profile with plot_profile (default False; metafor's default is TRUE). Several profiles are drawn in a grid of panels.

False
ax Axes | None

Matplotlib axes to draw on (with plot=True). Default: a new figure.

None
sub1 bool

Number the scale coefficients in the axis label and title of the plot from 0, so that the first is alpha[0] instead of alpha[1] (metafor's undocumented sub1 argument).

False
LB bool

Accepted as in metafor, where it chooses parLapplyLB; it changes no result.

False
**plot_args Any

Further keyword arguments passed on to plot_profile (pch, cline, refline, xlab, ylab, main, log, cex, lwd), as metafor's ... is to plot.profile.rma; they are not used (and not checked) with plot=False.

{}

Returns:

Type Description
LSProfileResult | list[LSProfileResult]

The profile (an LSProfileResult with the grid alpha, the log-likelihoods ll, beta, ci_lb, ci_ub, ylim, vc,

LSProfileResult | list[LSProfileResult]

maxll and position), or a list of them (a ProfileList) when several scale coefficients are profiled.

Raises:

Type Description
InputError

the model was fitted with optbeta=True or has no estimated scale coefficient; alpha is out of range or fixed; steps has missing values or is a single number below 2; xlim or ylim does not have length 2; parallel is not one of the accepted values or ncpus is below 1.

Metafor reference

profile.rma

profile_rma_mv

profile_rma_mv(
    fitted: RMAMVResult,
    sigma2: int | None = None,
    tau2: int | None = None,
    rho: int | None = None,
    gamma2: int | None = None,
    phi: int | None = None,
    xlim: Sequence[float] | None = None,
    ylim: Sequence[float] | None = None,
    steps: int | ArrayLike = 20,
    lltol: float = 0.001,
    progbar: bool = False,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    plot: bool = False,
    *,
    exp: bool = False,
    ax: Any = None,
    startmethod: Any = None,
    LB: bool = False,
    **plot_args: Any,
) -> MVProfileResult | list[MVProfileResult]

Profile the likelihood of an rma_mv fit over one variance or correlation component (metafor's profile.rma.mv).

Without any of sigma2, tau2, rho, gamma2 and phi every estimated component is profiled and a list is returned (a single result if there is just one; several are a ProfileList). xlim defaults to metafor's range around the estimate: for a variance a quarter to four times the estimate (half to twice for tau2 and gamma2 with a spatial structure), at least up to 0.1; for a correlation the estimate +- 0.5 within (-1, 1) (from 0 for 'CAR', half to twice the estimate for the spatial structures).

R source: https://github.com/wviechtb/metafor/blob/master/R/profile.rma.mv.r

Parameters:

Name Type Description Default
fitted RMAMVResult

Model fitted by rma_mv.

required
sigma2 int | None

0-based position of the sigma2 component to profile (metafor counts from 1). Only one of sigma2, tau2, rho, gamma2 and phi may be given.

None
tau2 int | None

0-based position of the tau2 component to profile.

None
rho int | None

0-based position of the rho component to profile.

None
gamma2 int | None

0-based position of the gamma2 component to profile.

None
phi int | None

0-based position of the phi component to profile.

None
xlim Sequence[float] | None

Range (lower, upper) of the profiled values of the component, within the parameter space (a variance at least 0, a correlation within -1 and 1, at least 0 for 'CAR' and the spatial structures). Default: metafor's range around the estimate.

None
ylim Sequence[float] | None

Range (lower, upper) of the profile log-likelihood stored in the result (and drawn by the plot). Default: the range of the profile and the maximum.

None
steps int | ArrayLike

Number of equally spaced values in xlim to profile over (a single number, at least 2), or a sequence of two or more values to profile at (then xlim defaults to their range). Missing values are not allowed.

20
lltol float

Tolerance when checking whether a profiled log-likelihood exceeds that of the fitted model (a warning is given if it does).

0.001
progbar bool

Print a progress bar to stderr while the models of the grid are fitted (default False; metafor's default is TRUE).

False
parallel Literal['no', 'snow', 'multicore']

Parallel fitting of the grid: 'no' (default), 'snow' or 'multicore'; both use a process pool ('multicore' forks the workers where the platform allows). As in metafor, 'no' with ncpus > 1 (or with cl) is 'snow', and 'snow' or 'multicore' with ncpus < 2 and no cl runs serially. The result equals that of the serial run. Any other value raises an InputError.

'no'
ncpus int

Number of worker processes (at least 1).

1
cl Executor | None

Executor to run the fits on instead of creating a process pool of ncpus workers.

None
plot bool

Draw the profile with plot_profile (default False; metafor's default is TRUE).

False
exp bool

Report the likelihood instead of the log-likelihood (exponentiate it; ylim is then not widened by 0.1).

False
ax Any

Matplotlib axes to draw on (with plot=True). Default: a new figure.

None
startmethod Any

Deprecated in metafor; giving it only warns.

None
LB bool

Accepted as in metafor, where it chooses parLapplyLB; it changes no result.

False
**plot_args Any

Further keyword arguments passed on to plot_profile (pch, cline, refline, xlab, ylab, main, log, cex, lwd), as metafor's ... is to plot.profile.rma; they are not used (and not checked) with plot=False.

{}

Returns:

Type Description
MVProfileResult | list[MVProfileResult]

The profile, a MVProfileResult, or a list of them when several components are profiled.

Raises:

Type Description
InputError

more than one component is given; the model has no such (estimated) component or the position does not exist or is fixed; no component can be profiled; steps has missing values or is a single number below 2; xlim or ylim does not have length 2 or xlim leaves the parameter space; parallel is not one of the accepted values or ncpus is below 1.

Metafor reference

profile.rma

ProfileResult dataclass

ProfileResult(
    tau2: FloatArray,
    ll: FloatArray,
    beta: DataFrame,
    ci_lb: DataFrame,
    ci_ub: DataFrame,
    xlim: tuple[float, float],
    ylim: tuple[float, float],
    method: str,
    vc: float,
    maxll: float,
    I2: FloatArray,
    H2: FloatArray,
    exp: bool = False,
    sqrt: bool = False,
    pred: DataFrame | None = None,
    pred_ci_lb: DataFrame | None = None,
    pred_ci_ub: DataFrame | None = None,
    pred_pi_lb: DataFrame | None = None,
    pred_pi_ub: DataFrame | None = None,
    blup: DataFrame | None = None,
    blup_se: DataFrame | None = None,
    blup_pi_lb: DataFrame | None = None,
    blup_pi_ub: DataFrame | None = None,
)

Profile log-likelihood of tau^2 (or tau with sqrt=True), as returned by profile. to_frame() gives the grid and the log-likelihoods.

Attributes:

Name Type Description
tau2 FloatArray

The grid of profiled values (tau values for sqrt=True, which are then also in the tau property; reading tau otherwise raises AttributeError).

ll FloatArray

Profile (log-)likelihood at each grid value.

beta DataFrame

Coefficient estimates at each grid value (one row per grid value, one column per coefficient).

ci_lb DataFrame

Lower confidence interval bounds of the coefficients at each grid value.

ci_ub DataFrame

Upper confidence interval bounds of the coefficients at each grid value.

xlim tuple[float, float]

Range (lower, upper) of the profiled values.

ylim tuple[float, float]

Range (lower, upper) of the (log-)likelihood used for the plot.

method str

Estimation method of the model.

vc float

The model's own estimate of the profiled parameter (tau with sqrt=True).

maxll float

(Restricted) log-likelihood of the fitted model (its exponential with exp=True).

I2 FloatArray

Estimates of I^2 at each grid value.

H2 FloatArray

Estimates of H^2 at each grid value.

exp bool

Whether ll is the likelihood rather than the log-likelihood.

sqrt bool

Whether the profile is over tau rather than tau^2.

pred DataFrame | None

With pred=True: predicted values at each grid value (one row per prediction, one column per grid value).

pred_ci_lb DataFrame | None

With pred=True: lower confidence bounds of the predictions.

pred_ci_ub DataFrame | None

With pred=True: upper confidence bounds of the predictions.

pred_pi_lb DataFrame | None

With pred=True: lower prediction interval bounds.

pred_pi_ub DataFrame | None

With pred=True: upper prediction interval bounds.

blup DataFrame | None

With blup=True: BLUPs at each grid value (one row per study).

blup_se DataFrame | None

With blup=True: standard errors of the BLUPs.

blup_pi_lb DataFrame | None

With blup=True: lower prediction interval bounds of the BLUPs.

blup_pi_ub DataFrame | None

With blup=True: upper prediction interval bounds of the BLUPs.

comps property

comps: int

metafor's comps: the number of variance components profiled (one).

xlab property

xlab: str

The label of the x axis of the profile plot.

title property

title: str

The title of the profile plot.

tau property

tau: FloatArray

The grid of tau values (metafor names the grid tau for sqrt=TRUE).

Raises:

Type Description
AttributeError

the profile is of tau^2.

SelProfileResult dataclass

SelProfileResult(
    tau2: FloatArray,
    ll: FloatArray,
    beta: DataFrame,
    ci_lb: DataFrame,
    ci_ub: DataFrame,
    xlim: tuple[float, float],
    ylim: tuple[float, float],
    method: str,
    vc: float,
    maxll: float,
    I2: FloatArray,
    H2: FloatArray,
    exp: bool = False,
    sqrt: bool = False,
    pred: DataFrame | None = None,
    pred_ci_lb: DataFrame | None = None,
    pred_ci_ub: DataFrame | None = None,
    pred_pi_lb: DataFrame | None = None,
    pred_pi_ub: DataFrame | None = None,
    blup: DataFrame | None = None,
    blup_se: DataFrame | None = None,
    blup_pi_lb: DataFrame | None = None,
    blup_pi_ub: DataFrame | None = None,
    comp: str = 'tau2',
    delta_pos: int = 0,
    deltas: int = 1,
)

Bases: ProfileResult

Profile log-likelihood of tau^2 or of one selection parameter of a selmodel fit. It has the attributes of ProfileResult, with tau2 holding the grid of the profiled component (also through the delta property for a selection parameter, which raises AttributeError for a tau^2 profile); I2 and H2 are NaN.

Attributes:

Name Type Description
comp str

The profiled component, 'tau2' or 'delta'.

delta_pos int

0-based position of the profiled selection parameter (0 for a tau^2 profile).

deltas int

Number of selection parameters of the model.

delta property

delta: FloatArray

The grid of a selection parameter profile.

Raises:

Type Description
AttributeError

the profile is of tau^2.

MVProfileResult dataclass

MVProfileResult(
    tau2: FloatArray,
    ll: FloatArray,
    beta: DataFrame,
    ci_lb: DataFrame,
    ci_ub: DataFrame,
    xlim: tuple[float, float],
    ylim: tuple[float, float],
    method: str,
    vc: float,
    maxll: float,
    I2: FloatArray,
    H2: FloatArray,
    exp: bool = False,
    sqrt: bool = False,
    pred: DataFrame | None = None,
    pred_ci_lb: DataFrame | None = None,
    pred_ci_ub: DataFrame | None = None,
    pred_pi_lb: DataFrame | None = None,
    pred_pi_ub: DataFrame | None = None,
    blup: DataFrame | None = None,
    blup_se: DataFrame | None = None,
    blup_pi_lb: DataFrame | None = None,
    blup_pi_ub: DataFrame | None = None,
    comp: str = 'sigma2',
    comp_pos: int = 0,
    comp_n: int = 1,
)

Bases: ProfileResult

Profile log-likelihood of one variance or correlation component of an rma_mv fit. It has the attributes of ProfileResult, with tau2 holding the grid of the profiled component (whatever it is, also through the property named like the component: sigma2, rho, gamma2 or phi; the others raise AttributeError); I2 and H2 are NaN.

Attributes:

Name Type Description
comp str

Name of the profiled component: 'sigma2', 'tau2', 'rho', 'gamma2' or 'phi'.

comp_pos int

0-based position of the profiled component.

comp_n int

Number of components of that kind in the model.

sigma2 property

sigma2: FloatArray

The grid of a sigma2 profile (metafor stores it under the name of the component).

rho property

rho: FloatArray

The grid of a rho profile.

gamma2 property

gamma2: FloatArray

The grid of a gamma2 profile.

phi property

phi: FloatArray

The grid of a phi profile.

xlab property

xlab: str

The label of the x axis of the profile plot.

title property

title: str

The title of the profile plot.

vif

vif(res: Any, *args: Any, **kwargs: Any) -> VIFResult

Variance inflation factors for a fitted meta-regression model (metafor's vif).

This is a single-dispatch function: the implementation is chosen by the class of res. See vif_rma_uni, vif_rma_mv, vif_rma_ls and vif_selmodel.

Parameters:

Name Type Description Default
res Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation.

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
VIFResult

The (G)VIFs, a VIFResult (for a location-scale model an LSVIFResult with the two parts, if both have predictors).

Raises:

Type Description
ArgumentError

there is no implementation for the class of res.

InputError

raised by the implementation for an invalid argument.

TypeError

the implementation does not accept a keyword argument.

vif_rma_uni

vif_rma_uni(
    res: RMAResult,
    btt: int
    | str
    | Sequence[int | str | Sequence[int]]
    | None = None,
    att: Any = None,
    table: bool = False,
    reestimate: bool = False,
    sim: bool | int = False,
    progbar: bool = True,
    seed: int | None = None,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    digits: int | None = None,
    intercept: bool = False,
    fixed: bool = False,
    joinb: Sequence[Any] | None = None,
    LB: bool = False,
    joina: Sequence[Any] | None = None,
) -> VIFResult

(Generalized) variance inflation factors for the coefficients of an rma_uni meta-regression (metafor's vif.rma).

A VIF of a coefficient (or a GVIF of a set of coefficients) shows how much the variance of its estimate is inflated by correlation with the other moderators; the SIF is the corresponding inflation of the standard error.

R source: https://github.com/wviechtb/metafor/blob/master/R/vif.rma.r

Parameters:

Name Type Description Default
res RMAResult

Model fitted by rma_uni with moderators (a robust result is accepted, but not with sim or reestimate).

required
btt int | str | Sequence[int | str | Sequence[int]] | None

Sets of location coefficients to compute a (generalized) VIF for, 0-based: an int, a string searched for (Python re.search) in the coefficient names, or a list of ints gives one set (one GVIF); a list with lists or strings among its elements gives one set per element (btt=[1, [2, 3], 4], like metafor's btt=list(2, 3:4, 5)). Default: each coefficient except the intercept gets its own VIF.

None
att Any

Must be None: metafor uses it for location-scale models only and so does vif_rma_ls; any other value raises an InputError.

None
table bool

Add the VIFs to the coefficient table (table of the result; ignored when btt is given).

False
reestimate bool

Refit the model with only the coefficients of each set when computing its (G)VIF.

False
sim bool | int

Simulate the distribution of each (G)VIF under independence: True for 1000 iterations or a number of iterations (at least 2). The model is refitted with independently permuted variables of the data (a model given as a formula with data) or columns of the model matrix; the result then has sim and prop (nothing is simulated if every (G)VIF is 1). Iteration l is seeded with seed + l when seed is given, as in metafor, otherwise from the stream of set_seed.

False
progbar bool

Print a progress bar to stderr while simulating (sim). Default True, as in metafor.

True
seed int | None

Seed for the simulation (sim). Default: the stream of set_seed is continued.

None
parallel Literal['no', 'snow', 'multicore']

Parallel simulation: 'no' (default), 'snow' or 'multicore'; both use a process pool of ncpus workers ('multicore' forks them where the platform allows). As in metafor, 'no' with ncpus > 1 (or with cl) is 'snow', and 'snow' or 'multicore' with ncpus < 2 and no cl runs serially. Any other value raises an InputError.

'no'
ncpus int

Number of worker processes (at least 1).

1
cl Executor | None

Executor to run the iterations on instead of a process pool.

None
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
intercept bool

Include the intercept among the coefficients (it is left out by default).

False
fixed bool

Match a string btt literally instead of as a regular expression.

False
joinb Sequence[Any] | None

One label per column of the model matrix; with sim the columns that share a label are permuted together (then the columns of the model matrix are permuted, not the data).

None
LB bool

Accepted as in metafor, where it balances the load of a 'snow' cluster; it changes nothing here.

False
joina Sequence[Any] | None

Accepted and unused (metafor uses it for location-scale models only).

None

Returns:

Type Description
VIFResult

The (G)VIFs, a VIFResult with one VIFEntry per coefficient or set (vif, sif, m), the

VIFResult

optional coefficient table and, with sim, the simulated values sim and the proportions prop.

Raises:

Type Description
InputError

the model has no moderators; att is given; sim is a number below 2 or sim or reestimate is used with a robust result; btt is the intercept (without intercept=True), is out of range or matches no coefficient; joinb does not have one label per column of the model matrix; parallel is not an accepted value or ncpus is below 1.

Metafor reference

vif

vif_rma_ls

vif_rma_ls(
    res: RMALSResult,
    btt: int
    | str
    | Sequence[int | str | Sequence[int]]
    | None = None,
    att: int
    | str
    | Sequence[int | str | Sequence[int]]
    | None = None,
    table: bool = False,
    reestimate: bool = False,
    sim: bool | int = False,
    progbar: bool = True,
    seed: int | None = None,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    digits: int | None = None,
    intercept: bool = False,
    fixed: bool = False,
    joinb: Sequence[Any] | None = None,
    joina: Sequence[Any] | None = None,
    LB: bool = False,
) -> VIFResult | LSVIFResult

(Generalized) variance inflation factors for the location and, if the scale model has predictors, the scale coefficients of a location-scale model (metafor's vif.rma).

Unlike metafor, a model given by formulas has its model matrix columns permuted for sim (sim_type == 'X'), not the underlying data variables. The location part is left out if the location model has only an intercept, the scale part if the scale model has.

R source: https://github.com/wviechtb/metafor/blob/master/R/vif.rma.r

Parameters:

Name Type Description Default
res RMALSResult

Location-scale model fitted by rma_uni with scale.

required
btt int | str | Sequence[int | str | Sequence[int]] | None

Sets of location coefficients, as for vif: 0-based, an int, a string searched for (Python re.search) in the coefficient names, a list of ints, or a list of sets.

None
att int | str | Sequence[int | str | Sequence[int]] | None

Sets of scale coefficients, as btt.

None
table bool

Add the VIFs to the coefficient tables (table of the result; ignored for a part whose btt or att is given).

False
reestimate bool

Refit the model with only the coefficients of each set when computing its (G)VIF.

False
sim bool | int

Simulate the distribution of each (G)VIF under independence: True for 1000 iterations or a number of iterations. The model is refitted with independently permuted columns of the model matrix; the result then has sim and prop. Iteration l is seeded with seed + l when seed is given, as in metafor, otherwise from the stream of set_seed. The location and the scale part are permuted separately. The draws do not depend on parallel.

False
progbar bool

Print a progress bar to stderr while simulating (sim). Default True, as in metafor.

True
seed int | None

Seed for the simulation (sim). Default: the stream of set_seed is continued.

None
parallel Literal['no', 'snow', 'multicore']

Parallel simulation: 'no' (default), 'snow' or 'multicore'; both use a process pool of ncpus workers ('multicore' forks them where the platform allows). As in metafor, 'no' with ncpus > 1 (or with cl) is 'snow', and 'snow' or 'multicore' with ncpus < 2 and no cl runs serially. Any other value raises an InputError.

'no'
ncpus int

Number of worker processes (at least 1).

1
cl Executor | None

Executor to run the iterations on instead of a process pool.

None
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
intercept bool

Include the intercepts among the coefficients (they are left out by default).

False
fixed bool

Match a string btt or att literally instead of as a regular expression.

False
joinb Sequence[Any] | None

One label per column of the location model matrix; with sim the columns that share a label are permuted together.

None
joina Sequence[Any] | None

One label per column of the scale model matrix, as joinb.

None
LB bool

Accepted as in metafor, where it balances the load of a 'snow' cluster; it changes nothing here.

False

Returns:

Type Description
VIFResult | LSVIFResult

A VIFResult when only the location or the scale part has predictors, otherwise an LSVIFResult holding the results of

VIFResult | LSVIFResult

both parts as beta and alpha (the scale part has attspec).

Raises:

Type Description
InputError

neither the location nor the scale model has predictors; sim is a number below 2; btt or att is invalid (the intercept without intercept=True, out of range or matching no coefficient); joinb or joina does not have one label per column; parallel is not an accepted value or ncpus is below 1.

InternalError

no VIFs were computed.

Metafor reference

vif

vif_rma_mv

vif_rma_mv(
    res: RMAMVResult,
    btt: int
    | str
    | Sequence[int | str | Sequence[int]]
    | None = None,
    att: Any = None,
    table: bool = False,
    reestimate: bool = False,
    sim: bool | int = False,
    progbar: bool = True,
    seed: int | None = None,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    digits: int | None = None,
    intercept: bool = False,
    fixed: bool = False,
    joinb: Sequence[Any] | None = None,
    LB: bool = False,
    joina: Sequence[Any] | None = None,
) -> VIFResult

(Generalized) variance inflation factors for the coefficients of an rma_mv meta-regression, as vif for rma_uni fits (metafor's vif.rma).

With sim the moderators are permuted as the variables of the data when they were given as a formula, otherwise as the columns of the model matrix.

R source: https://github.com/wviechtb/metafor/blob/master/R/vif.rma.r

Parameters:

Name Type Description Default
res RMAMVResult

Model fitted by rma_mv with moderators.

required
btt int | str | Sequence[int | str | Sequence[int]] | None

Sets of location coefficients to compute a (generalized) VIF for, 0-based: an int, a string searched for (Python re.search) in the coefficient names, or a list of ints gives one set (one GVIF); a list with lists or strings among its elements gives one set per element (btt=[1, [2, 3], 4], like metafor's btt=list(2, 3:4, 5)). Default: each coefficient except the intercept gets its own VIF.

None
att Any

Must be None (metafor uses it for location-scale models only); any other value raises an InputError.

None
table bool

Add the VIFs to the coefficient table (table of the result; ignored when btt is given).

False
reestimate bool

Refit the model with only the coefficients of each set; the variance components are re-estimated.

False
sim bool | int

Simulate the distribution of each (G)VIF under independence: True for 1000 iterations or a number of iterations (at least 2). The model is refitted with independently permuted variables of the data (a model given as a formula with data) or columns of the model matrix; the result then has sim and prop. A warning is given, and nothing simulated, if redundant predictors were dropped. Iteration l is seeded with seed + l when seed is given, as in metafor, otherwise from the stream of set_seed.

False
progbar bool

Print a progress bar to stderr while simulating (sim). Default True, as in metafor.

True
seed int | None

Seed for the simulation (sim). Default: the stream of set_seed is continued.

None
parallel Literal['no', 'snow', 'multicore']

Parallel simulation: 'no' (default), 'snow' or 'multicore'; both use a process pool of ncpus workers ('multicore' forks them where the platform allows). As in metafor, 'no' with ncpus > 1 (or with cl) is 'snow', and 'snow' or 'multicore' with ncpus < 2 and no cl runs serially. Any other value raises an InputError.

'no'
ncpus int

Number of worker processes (at least 1).

1
cl Executor | None

Executor to run the iterations on instead of a process pool.

None
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
intercept bool

Include the intercept among the coefficients (it is left out by default).

False
fixed bool

Match a string btt literally instead of as a regular expression.

False
joinb Sequence[Any] | None

One label per column of the model matrix; with sim the columns that share a label are permuted together.

None
LB bool

Accepted as in metafor, where it balances the load of a 'snow' cluster; it changes nothing here.

False
joina Sequence[Any] | None

Accepted and unused, as in metafor.

None

Returns:

Type Description
VIFResult

The (G)VIFs, a VIFResult.

Raises:

Type Description
InputError

the model has no moderators; att is given; sim is a number below 2; btt is invalid (the intercept without intercept=True, out of range or matching no coefficient); parallel is not an accepted value or ncpus is below 1.

Metafor reference

vif

vif_selmodel

vif_selmodel(
    res: SelmodelResult,
    btt: int
    | str
    | Sequence[int | str | Sequence[int]]
    | None = None,
    att: Any = None,
    table: bool = False,
    reestimate: bool = False,
    sim: bool | int = False,
    progbar: bool = True,
    seed: int | None = None,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    digits: int | None = None,
    intercept: bool = False,
    fixed: bool = False,
    joinb: Sequence[Any] | None = None,
    LB: bool = False,
    joina: Sequence[Any] | None = None,
) -> VIFResult

(Generalized) variance inflation factors for the coefficients of a selmodel fit with moderators, computed from the variance-covariance matrix of the coefficients (metafor's vif.rma).

As in metafor, sim and reestimate are not available for these fits.

R source: https://github.com/wviechtb/metafor/blob/master/R/vif.rma.r

Parameters:

Name Type Description Default
res SelmodelResult

Selection model fitted by selmodel with moderators.

required
btt int | str | Sequence[int | str | Sequence[int]] | None

Sets of location coefficients to compute a (generalized) VIF for, 0-based: an int, a string searched for (Python re.search) in the coefficient names, or a list of ints gives one set (one GVIF); a list with lists or strings among its elements gives one set per element (btt=[1, [2, 3], 4], like metafor's btt=list(2, 3:4, 5)). Default: each coefficient except the intercept gets its own VIF.

None
att Any

Must be None (metafor uses it for location-scale models only); any other value raises an InputError.

None
table bool

Add the VIFs to the coefficient table (table of the result; ignored when btt is given).

False
reestimate bool

Not available for selection models; requesting it raises an error.

False
sim bool | int

Not available for selection models; requesting it raises an error.

False
progbar bool

Accepted and unused.

True
seed int | None

Accepted and unused.

None
parallel Literal['no', 'snow', 'multicore']

Accepted and unused.

'no'
ncpus int

Accepted and unused.

1
cl Executor | None

Accepted and unused.

None
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
intercept bool

Include the intercept among the coefficients (it is left out by default).

False
fixed bool

Match a string btt literally instead of as a regular expression.

False
joinb Sequence[Any] | None

Accepted and unused.

None
LB bool

Accepted and unused.

False
joina Sequence[Any] | None

Accepted and unused.

None

Returns:

Type Description
VIFResult

The (G)VIFs, a VIFResult.

Raises:

Type Description
InputError

the model has no moderators; att is given; sim (a number of 2 or more) or reestimate is requested; btt is invalid (the intercept without intercept=True, out of range or matching no coefficient).

Metafor reference

vif

VIFResult dataclass

VIFResult(
    vif: tuple[VIFEntry, ...],
    bttspec: bool,
    digits: int = 4,
    table: DataFrame | None = None,
    test: str | None = None,
    sim: FloatArray | None = None,
    sim_type: str | None = None,
    prop: FloatArray | None = None,
    attspec: bool | None = None,
)

(Generalized) variance inflation factors and standard error inflation factors, as returned by vif (metafor's vif.rma object). vifs and sifs give them as Series and to_frame() as a data frame.

Attributes:

Name Type Description
vif tuple[VIFEntry, ...]

One VIFEntry per coefficient or set of coefficients.

bttspec bool

Whether the sets were chosen with btt.

digits int

Number of decimals of the printout.

table DataFrame | None

The coefficient table with the VIFs added (table=True), or None.

test str | None

Test of the model ('z', 't', 'knha' or 'adhoc') when table is given, else None.

sim FloatArray | None

Simulated (G)VIFs under independence: one row per iteration, one column per coefficient set (sim was given), or None.

sim_type str | None

What was permuted in the simulation: 'data' (the variables of the data, for a model given as a formula) or 'X' (the columns of the model matrix); None without sim.

prop FloatArray | None

For each set, the proportion of the simulated (G)VIFs that are at most as large as the observed one (as metafor computes it, vif >= sim), or None.

attspec bool | None

For the scale part of a location-scale model: whether the sets were chosen with att.

attspec class-attribute instance-attribute

attspec: bool | None = None

not alpha_missing of the scale part of a location-scale model; metafor stores it as attspec there (and bttspec for the location part).

vifs property

vifs: Series

(G)VIFs indexed by coefficient name (or by coefs when btt was given).

to_frame

to_frame() -> DataFrame

As metafor's as.data.frame.vif.rma.

summary

summary(
    digits: int | None = None, *, num: bool = False
) -> str

The printout of print(x, digits=, num=): num numbers the rows of the table of coefficients (table=True).

VIFEntry dataclass

VIFEntry(
    spec: str,
    coefs: str,
    coefname: str,
    m: int,
    vif: float,
    sif: float,
)

The (G)VIF of one coefficient or one set of coefficients, an element of VIFResult.

Attributes:

Name Type Description
spec str

The specification of the set, formatted as in metafor's printout (the 1-based number(s) of the coefficients, or the string given as btt).

coefs str

The coefficients of the set, 1-based as metafor prints them.

coefname str

Name of the coefficient (empty for a set of several).

m int

Number of coefficients in the set.

vif float

The (generalized) variance inflation factor.

sif float

The (generalized) standard error inflation factor, vif ** (1 / (2 * m)).

Cluster-robust inference

robust

robust(model: Any, *args: Any, **kwargs: Any) -> Any

Cluster-robust (sandwich) inference for a fitted model (metafor's robust).

This is a single-dispatch function: the implementation is chosen by the class of model. See robust_rma_uni and robust_rma_mv.

Parameters:

Name Type Description Default
model Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation (cluster first).

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
Any

A copy of the model with cluster-robust standard errors, tests and confidence intervals.

Raises:

Type Description
ArgumentError

there is no implementation for the class of model.

InputError

raised by the implementation for an invalid argument.

TypeError

cluster is missing, more than one positional argument is given or a keyword argument is not accepted.

robust_rma_uni

robust_rma_uni(
    model: RMAResult,
    cluster: Cluster,
    *,
    adjust: bool | str = True,
    club_sandwich: bool | None = None,
    vcov: str | None = None,
    coef_test: str | None = None,
    conf_test: str | None = None,
    wald_test: str | None = None,
    clubSandwich: bool | None = None,
    digits: int | Mapping[str, int] | None = None,
    verbose: bool = False,
) -> RMAResult

Cluster-robust inference for an rma_uni fit (metafor's robust.rma.uni).

The variance-covariance matrix of the coefficients is replaced by a sandwich estimator that is robust to correlated errors within clusters; tests and confidence intervals use it.

R source: https://github.com/wviechtb/metafor/blob/master/R/robust.rma.uni.r

Parameters:

Name Type Description Default
model RMAResult

Model fitted by rma_uni (also a model that was made robust before).

required
cluster Cluster

The clustering variable: the name of a column of the data given to the model, or a vector with one value per row of the original data (before subsetting and removal of missing values; a vector with one value per study used in the fit is also accepted). It must not contain missing values.

required
adjust bool | str

Small-sample adjustment of the cluster-robust variance-covariance matrix: True (default; CR1, multiplies by n/(n-p), with n clusters and p coefficients), False (CR0), 'Stata1' (or 'Stata') or 'Stata2'. Not used with club_sandwich.

True
club_sandwich bool | None

Use the clubSandwich approach (bias-reduced linearization, Satterthwaite degrees of freedom) for the cluster-robust tests and intervals instead of the plain sandwich estimator. Default: False.

None
vcov str | None

With club_sandwich (ignored otherwise; this and the next three take exactly the values listed): the variance estimator, 'CR0', 'CR1', 'CR1p', 'CR1S', 'CR2' or 'CR3'. Default: 'CR2'.

None
coef_test str | None

With club_sandwich: the test of the coefficients, 'z', 'naive-t', 'naive-tp', 'Satterthwaite' or 'saddlepoint'. The saddlepoint test gives p-values only; the confidence intervals then use conf_test or Satterthwaite. Default: Satterthwaite.

None
conf_test str | None

With club_sandwich: the method for the confidence intervals, as coef_test without 'saddlepoint'. Default: that of coef_test.

None
wald_test str | None

With club_sandwich: the omnibus test, 'chi-sq', 'Naive-F', 'Naive-Fp', 'HTA', 'HTB', 'HTZ', 'EDF' or 'EDT'. Default: 'HTZ'.

None
clubSandwich bool | None

R's spelling of club_sandwich. Giving both with different values is an error.

None
digits int | Mapping[str, int] | None

Number of decimals of the printout of the result. Default: the digits option, else that of the model.

None
verbose bool

Accepted and ignored (metafor shows the errors of a failing clubSandwich computation).

False

Returns:

Type Description
RMAResult

The model with the cluster-robust variance-covariance matrix, standard errors, tests and confidence intervals, an RMAResult

RMAResult

of the same form as the input (its robust attribute is set; without club_sandwich the tests are t tests with n - p degrees of

RMAResult

freedom).

Raises:

Type Description
InputError

cluster cannot be found, has the wrong length or has missing values; adjust, vcov, coef_test, conf_test or wald_test is not an accepted value (including conf_test='saddlepoint'); club_sandwich and clubSandwich differ; without club_sandwich the number of clusters is not larger than the number of coefficients.

Metafor reference

robust

robust_rma_mv

robust_rma_mv(
    model: RMAMVResult,
    cluster: Cluster,
    *,
    adjust: bool | str = True,
    club_sandwich: bool | None = None,
    vcov: str | None = None,
    coef_test: str | None = None,
    conf_test: str | None = None,
    wald_test: str | None = None,
    clubSandwich: bool | None = None,
    digits: int | Mapping[str, int] | None = None,
    verbose: bool = False,
) -> RMAMVResult

Cluster-robust inference for an rma_mv fit (metafor's robust.rma.mv); the arguments are those of robust_rma_uni.

With club_sandwich=True (or R's spelling clubSandwich) the random effects must be nested within the clusters and R= matrices are not allowed.

R source: https://github.com/wviechtb/metafor/blob/master/R/robust.rma.mv.r

Parameters:

Name Type Description Default
model RMAMVResult

Model fitted by rma_mv.

required
cluster Cluster

The clustering variable: the name of a column of the data given to the model, or a vector with one value per row of the original data (before subsetting and removal of missing values; a vector with one value per study used in the fit is also accepted). It must not contain missing values.

required
adjust bool | str

Small-sample adjustment of the cluster-robust variance-covariance matrix: True (default; CR1, multiplies by n/(n-p), with n clusters and p coefficients), False (CR0), 'Stata1' (or 'Stata') or 'Stata2'. Not used with club_sandwich.

True
club_sandwich bool | None

Use the clubSandwich approach (bias-reduced linearization, Satterthwaite degrees of freedom) for the cluster-robust tests and intervals instead of the plain sandwich estimator. Default: False.

None
vcov str | None

With club_sandwich (ignored otherwise; this and the next three take exactly the values listed): the variance estimator, 'CR0', 'CR1', 'CR1p', 'CR1S', 'CR2' or 'CR3'. Default: 'CR2'.

None
coef_test str | None

With club_sandwich: the test of the coefficients, 'z', 'naive-t', 'naive-tp', 'Satterthwaite' or 'saddlepoint'. The saddlepoint test gives p-values only; the confidence intervals then use conf_test or Satterthwaite. Default: Satterthwaite.

None
conf_test str | None

With club_sandwich: the method for the confidence intervals, as coef_test without 'saddlepoint'. Default: that of coef_test.

None
wald_test str | None

With club_sandwich: the omnibus test, 'chi-sq', 'Naive-F', 'Naive-Fp', 'HTA', 'HTB', 'HTZ', 'EDF' or 'EDT'. Default: 'HTZ'.

None
clubSandwich bool | None

R's spelling of club_sandwich. Giving both with different values is an error.

None
digits int | Mapping[str, int] | None

Number of decimals of the printout of the result. Default: the digits option, else that of the model.

None
verbose bool

Accepted and ignored (metafor shows the errors of a failing clubSandwich computation).

False

Returns:

Type Description
RMAMVResult

The model with the cluster-robust variance-covariance matrix, standard errors, tests and confidence intervals, an

RMAMVResult

RMAMVResult of the same form as the input.

Raises:

Type Description
EstimationError

with club_sandwich, the marginal variance-covariance matrix cannot be inverted.

InputError

as for robust_rma_uni; with club_sandwich also: the model has fixed correlation matrices (R) or its random effects are not nested within the clusters.

Metafor reference

robust

Variance-covariance matrices and coefficient tables

vcov

vcov(
    object: Any,
    type: Literal[
        'fixed',
        'beta',
        'alpha',
        'delta',
        'obs',
        'marginal',
        'fitted',
        'resid',
    ] = 'fixed',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> DataFrame | dict[str, DataFrame]

Variance-covariance matrices of a fitted model (metafor's vcov).

Which matrix is returned depends on type; for 'obs', 'fitted' and 'resid' the frame has one row and column per study of the subset. A deltamethod or matreg result gives its own variance-covariance matrix (vcov.deltamethod, vcov.matreg).

Parameters:

Name Type Description Default
object Any

The fitted model (or a deltamethod or matreg result).

required
type Literal['fixed', 'beta', 'alpha', 'delta', 'obs', 'marginal', 'fitted', 'resid']

Which matrix: 'fixed' (default; of the coefficients), 'beta' (of the location coefficients), 'alpha' (of the scale coefficients of a location-scale model), 'delta' (of the selection parameters of a selection model), 'obs' (or 'marginal'; of the observed effects), 'fitted' (of the fitted values) or 'resid' (of the residuals). A unique prefix is enough ('f' is ambiguous). Not every type is available for every model.

'fixed'
na_action Literal['omit', 'exclude', 'pass', 'fail']

For 'obs', 'fitted' and 'resid': 'omit' (default) keeps the studies used in fitting, 'exclude' and 'pass' all of them (NaN for those not used) and 'fail' raises if any study was left out ('fitted' gives the whole matrix, as in R, and 'resid' always raises, as R fails there too).

'omit'

Returns:

Type Description
DataFrame | dict[str, DataFrame]

The variance-covariance matrix as a data frame labelled with the coefficient names or study labels; a dict of such frames for a model with several

DataFrame | dict[str, DataFrame]

parts and no specific type where that applies.

Raises:

Type Description
ArgumentError

object is not a fitted model, or type='resid' for a fit without hatvalues() (rma_mh, rma_peto, rma_glmm).

InputError

type (or an ambiguous prefix of it) or na_action is not valid, 'alpha' for a model without scale part, 'delta' for a model that is not a selection model, studies are missing and na_action='fail' for 'obs', or type='resid' with na_action='fail'.

NotSupportedError

'obs' for rma_mh, rma_peto and rma_glmm; 'resid' for robust and selection-model fits.

Metafor reference

vcov.rma

coef_summary

coef_summary(
    object: Any,
    type: Literal['beta', 'alpha', 'delta'] | None = None,
) -> DataFrame | dict[str, DataFrame]

The coefficient table of a fitted model as a data frame, as metafor's coef(summary(res)).

For a location-scale model the result is {'beta': ..., 'alpha': ...}, for a selection model {'beta': ..., 'delta': ...}; with type one table is returned.

Parameters:

Name Type Description Default
object Any

The fitted model (also the result of permutest, which gives its table with the permutation p-values).

required
type Literal['beta', 'alpha', 'delta'] | None

'beta' gives the table of the (location) coefficients of any fit, 'alpha' that of the scale coefficients of a location-scale model and 'delta' that of the selection parameters of a selection model. As in R, any other value is not an error: 'alpha' or 'delta' for a fit without that part gives what None gives (the table of the coefficients, or the dict for a location-scale or selection model). Default: all tables of the model (a dict for models with more than one).

None

Returns:

Type Description
DataFrame | dict[str, DataFrame]

A data frame with the columns estimate, se, zval (tval and df when the t distribution is used), pval, ci.lb and

DataFrame | dict[str, DataFrame]

ci.ub, one row per coefficient; a dict of frames for a location-scale or selection model without type.

Raises:

Type Description
ArgumentError

object is not a fitted model.

Residuals and influence

rstandard

rstandard(
    model: Any, *args: Any, **kwargs: Any
) -> ResidualResult

Internally standardised residuals of a fitted model (metafor's rstandard).

This is a single-dispatch function: the implementation is chosen by the class of model. See rstandard_rma_uni, rstandard_rma_mv, rstandard_rma_ls and rstandard_fixed_binary.

Parameters:

Name Type Description Default
model Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation (digits first).

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
ResidualResult

The residuals, a ResidualResult (a cluster result for rma_mv with cluster).

Raises:

Type Description
ArgumentError

there is no implementation for the class of model.

TypeError

the implementation does not accept a keyword argument.

rstandard_rma_uni

rstandard_rma_uni(
    model: RMAResult,
    digits: int | None = None,
    type: Literal['marginal', 'conditional'] = 'marginal',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> ResidualResult

Internally standardised residuals of an rma_uni fit (metafor's rstandard.rma.uni).

With type='marginal' the residuals y - X b are divided by the square roots of the diagonal of (I - H) M (I - H)', where M holds the marginal variances; with type='conditional' the residuals are those from the BLUPs, divided by their conditional standard errors. Conditional residuals are not available for models with non-standard weights.

R source: https://github.com/wviechtb/metafor/blob/master/R/rstandard.rma.uni.r

Parameters:

Name Type Description Default
model RMAResult

Model fitted by rma_uni (not a robust fit).

required
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
type Literal['marginal', 'conditional']

'marginal' (default) for marginal residuals or 'conditional' for conditional residuals (the deviations of the estimates from the BLUPs of the true effects). Exactly one of these two values (R also accepts a unique prefix).

'marginal'
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit' (default) drops them, 'exclude' and 'pass' keep one row per study with NaN for those left out, 'fail' raises an InputError if there are any. Corresponds to R's na.action option.

'omit'

Returns:

Type Description
ResidualResult

A ResidualResult with the residuals resid, their standard errors se and the standardised values z, labelled

ResidualResult

with the study labels.

Raises:

Type Description
ArgumentError

the model is not a fitted model.

InputError

type is not 'marginal' or 'conditional'; type='conditional' for a model with weights given or fitted without weighting; na_action is not valid, or is 'fail' and studies were left out of the fit.

NotSupportedError

the model is a robust result.

Metafor reference

residuals.rma

rstandard_fixed_binary

rstandard_fixed_binary(
    model: FixedBinaryResult,
    digits: int | None = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> ResidualResult

Standardised residuals (yi - beta) / sqrt(vi) of the individual tables of an rma_mh or rma_peto fit (metafor's rstandard.rma.mh and rstandard.rma.peto).

Parameters:

Name Type Description Default
model FixedBinaryResult

Model fitted by rma_mh or rma_peto.

required
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit' (default) drops them, 'exclude' and 'pass' keep one row per study with NaN for those left out, 'fail' raises an InputError if there are any. Corresponds to R's na.action option.

'omit'

Returns:

Type Description
ResidualResult

A ResidualResult with the residuals resid, their standard errors se and the standardised values z, labelled

ResidualResult

with the study labels.

Raises:

Type Description
InputError

na_action is not valid, or is 'fail' and tables have missing values (that is, their yi or vi is missing).

rstandard_rma_ls

rstandard_rma_ls(
    model: RMALSResult,
    digits: int = 4,
    type: Literal['marginal', 'conditional'] = 'marginal',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> ResidualResult

Internally standardised residuals of a location-scale fit (metafor's rstandard.rma.uni applied to an rma.ls object, which has no method of its own).

With type='marginal' the marginal residuals are divided by their standard errors, with type='conditional' the conditional ones (the deviations of the estimates from the BLUPs), both with the study-specific tau^2 of the model.

R source: https://github.com/wviechtb/metafor/blob/master/R/rstandard.rma.uni.r

Parameters:

Name Type Description Default
model RMALSResult

Location-scale model fitted by rma_uni with scale.

required
digits int

Number of decimals of the printout (default 4; unlike for rma_uni fits the digits of the model are not used).

4
type Literal['marginal', 'conditional']

'marginal' (default) for marginal residuals or 'conditional' for conditional residuals. Exactly one of these two values.

'marginal'
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit' (default) drops them, 'exclude' and 'pass' keep one row per study with NaN for those left out, 'fail' raises an InputError if there are any. Corresponds to R's na.action option.

'omit'

Returns:

Type Description
ResidualResult

A ResidualResult with the residuals resid, their standard errors se and the standardised values z, labelled

ResidualResult

with the study labels.

Raises:

Type Description
InputError

type is not 'marginal' or 'conditional'; type='conditional' for a model with weights given or fitted without weighting; na_action is not valid, or is 'fail' and studies were left out of the fit.

Metafor reference

residuals.rma

rstandard_rma_mv

rstandard_rma_mv(
    model: RMAMVResult,
    digits: int = 4,
    cluster: str | ArrayLike | None = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> ResidualResult | ClusterResidualResult

Internally standardised residuals of an rma_mv fit (metafor's rstandard.rma.mv).

The marginal residuals y - X b are divided by the square roots of the diagonal of (I - H) M (I - H)'. Unlike rma_uni, there is no type argument, as metafor gives only marginal residuals for rma.mv fits.

R source: https://github.com/wviechtb/metafor/blob/master/R/rstandard.rma.mv.r

Parameters:

Name Type Description Default
model RMAMVResult

Model fitted by rma_mv (not a robust fit).

required
digits int

Number of decimals of the printout (default 4; the digits of the model are not used).

4
cluster str | ArrayLike | None

A column name of the data or a vector with one value per row of the original data. With it the residuals of each cluster are also combined (statistic X2 = e' Var(e)^-1 e, NaN if the cluster's variance matrix is not positive definite). Default: none.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit' (default) drops them, 'exclude' and 'pass' keep one row per study with NaN for those left out, 'fail' raises an InputError if there are any. Corresponds to R's na.action option.

'omit'

Returns:

Type Description
ResidualResult | ClusterResidualResult

A ResidualResult with the residuals resid, their standard errors se and the standardised values z, labelled

ResidualResult | ClusterResidualResult

with the study labels. With cluster, a ClusterResidualResult holding that result per

ResidualResult | ClusterResidualResult

observation (obs) and per cluster, with each cluster's X2 statistic.

Raises:

Type Description
InputError

cluster cannot be found, has the wrong length or has missing values; na_action is not valid, or is 'fail' and studies were left out of the fit.

NotSupportedError

the model was passed through robust.

Metafor reference

residuals.rma

rstudent

rstudent(
    model: Any, *args: Any, **kwargs: Any
) -> ResidualResult

Externally standardised (studentised deleted) residuals of a fitted model (metafor's rstudent).

This is a single-dispatch function: the implementation is chosen by the class of model. See rstudent_rma_uni, rstudent_rma_mv and rstudent_fixed_binary.

Parameters:

Name Type Description Default
model Any

The fitted model. Its class selects the implementation.

required
*args Any

Positional arguments passed on to the implementation (digits first).

()
**kwargs Any

Keyword arguments passed on to the implementation.

{}

Returns:

Type Description
ResidualResult

The residuals, a ResidualResult (a cluster result for rma_mv with cluster).

Raises:

Type Description
ArgumentError

there is no implementation for the class of model (there is none for location-scale models).

TypeError

the implementation does not accept a keyword argument.

rstudent_rma_uni

rstudent_rma_uni(
    model: RMAResult,
    digits: int | None = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    progbar: bool = False,
) -> ResidualResult

Externally standardised residuals of an rma_uni fit (metafor's rstudent.rma.uni).

The deleted residual y_i - x_i' beta_(-i) compares each study with the prediction from the model fitted without it; its standard error adds the sampling variance, tau^2 and the variance of the prediction.

R source: https://github.com/wviechtb/metafor/blob/master/R/rstudent.rma.uni.r

Parameters:

Name Type Description Default
model RMAResult

Model fitted by rma_uni.

required
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit' (default) drops them, 'exclude' and 'pass' keep one row per study with NaN for those left out, 'fail' raises an InputError if there are any. Corresponds to R's na.action option.

'omit'
progbar bool

Print a progress bar to stderr while the studies are left out in turn (default False, as in metafor).

False

Returns:

Type Description
ResidualResult

A ResidualResult with the deleted residuals resid, their standard errors se and the standardised values z,

ResidualResult

labelled with the study labels.

Raises:

Type Description
ArgumentError

the model is not a fitted model.

InputError

na_action is not valid, or is 'fail' and studies were left out of the fit; the model has a single study.

NotSupportedError

the model is a robust result.

Metafor reference

residuals.rma

rstudent_fixed_binary

rstudent_fixed_binary(
    model: FixedBinaryResult,
    digits: int | None = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    progbar: bool = False,
) -> ResidualResult

Externally standardised residuals of an rma_mh or rma_peto fit: each table is compared with the pooled estimate from the other tables (metafor's rstudent.rma.mh and rstudent.rma.peto).

Parameters:

Name Type Description Default
model FixedBinaryResult

Model fitted by rma_mh or rma_peto.

required
digits int | None

Number of decimals of the printout. Default: the digits option, else that of the model.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

What to do with studies left out of the fit because of missing values: 'omit' (default) drops them, 'exclude' and 'pass' keep one row per study with NaN for those left out, 'fail' raises an InputError if there are any. Corresponds to R's na.action option.

'omit'
progbar bool

Print a progress bar to stderr while the tables are left out in turn (default False, as in metafor).

False

Returns:

Type Description
ResidualResult

A ResidualResult with the deleted residuals resid, their standard errors se and the standardised values z,

ResidualResult

labelled with the study labels.

Raises:

Type Description
InputError

na_action is not valid, or is 'fail' and tables have missing values.

rstudent_rma_mv

rstudent_rma_mv(
    model: RMAMVResult,
    digits: int = 4,
    progbar: bool = False,
    cluster: str | ArrayLike | None = None,
    reestimate: bool = True,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    LB: bool = False,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> ResidualResult | ClusterResidualResult

Externally standardised (deleted) residuals of an rma.mv fit (metafor's rstudent.rma.mv).

Each observation's residual is computed from the fit without it (without its whole cluster if cluster is given); the variance of the deleted residual is the marginal variance of the deleted observation(s) (computed with the variance components estimated without them) plus the variance of their predicted values from the fit without them. With cluster a ClusterResidualResult is returned, which also holds each cluster's X2 statistic.

Parameters:

Name Type Description Default
model RMAMVResult

A model fitted by rma_mv; not allowed for a model passed through robust.

required
digits int

Number of decimals used when the result is printed (default 4).

4
progbar bool

Print a progress bar to stderr while the refits are made (default False).

False
cluster str | ArrayLike | None

Clustering variable: a column name of the data the model was fitted to, or a vector with one value per row of that data (before subsetting and removal of rows with missing values, which are applied to it automatically). Whole clusters are then deleted in turn. None (the default) deletes each observation in turn.

None
reestimate bool

Re-estimate the variance and correlation components after each deletion (default True). With False they stay at the full-model values, which is faster and only approximate.

True
parallel Literal['no', 'snow', 'multicore']

'no' (the default), 'snow' or 'multicore'; run the refits in a process pool (see ncpus).

'no'
ncpus int

Number of worker processes (default 1; a value above 1 turns parallel processing on).

1
cl Executor | None

An executor to run the refits on, instead of one created for the call.

None
LB bool

metafor reads this undocumented extra argument to use load-balanced scheduling with parallel='snow'; accepted here and ignored.

False
na_action Literal['omit', 'exclude', 'pass', 'fail']

How observations dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of missing values for each) or 'fail' (raise an error).

'omit'

Returns:

Type Description
ResidualResult | ClusterResidualResult

A ResidualResult with the deleted residuals resid, their standard errors se and z-values z per

ResidualResult | ClusterResidualResult

observation; with cluster, a ClusterResidualResult that adds the X2

ResidualResult | ClusterResidualResult

statistic and the number of observations k of each cluster.

Raises:

Type Description
InputError

an argument or the data is invalid.

NotSupportedError

the model was passed through robust.

Metafor reference

residuals.rma

influence

influence(model: Any, *args: Any, **kwargs: Any) -> Any

Case-deletion (leave-one-out) diagnostics for a fitted model.

This is a single-dispatch function: the implementation is chosen from the class of model. For a model fitted by rma_uni see influence_rma_uni; for one fitted by rma_mv see influence_rma_mv, which is not available (as in metafor).

Parameters:

Name Type Description Default
model Any

A fitted model object.

required
*args Any

Positional arguments passed to the implementation chosen by the class of model.

()
**kwargs Any

Keyword arguments passed to the implementation chosen by the class of model.

{}

Returns:

Type Description
Any

What the implementation returns; for rma_uni fits an InfluenceResult.

Raises:

Type Description
ArgumentError

an argument has the wrong type or is not accepted.

Metafor reference

influence.rma.uni

influence_rma_uni

influence_rma_uni(
    model: RMAResult,
    digits: int | None = None,
    *,
    btt: int | Sequence[int] | str | None = None,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    measure: str = 'all',
    progbar: bool = False,
) -> InfluenceResult | Series | DataFrame | ResidualResult

Leave-one-out diagnostics for an rma.uni fit (metafor's influence()).

The model is refitted without each study in turn, which gives the externally standardised residuals, DFFITS, Cook's distances, covariance ratios, DFBETAS, leave-one-out tau^2 and QE, hat values and weights (Viechtbauer & Cheung, 2010, doi:10.1002/jrsm.11). Studies whose refit fails (or loses a coefficient) get NaN.

Parameters:

Name Type Description Default
model RMAResult

A model fitted by rma_uni; not allowed for a model passed through robust (except with measure='cooks.distance').

required
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
btt int | Sequence[int] | str | None

The coefficients Cook's distance and the covariance ratio refer to, as 0-based indices (or a regular expression matched against the coefficient names). None (the default) uses all coefficients.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

How studies dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of missing values for each, so the result has one row per supplied study) or 'fail' (raise an error).

'omit'
measure str

Metafor's undocumented argument that restricts the result: 'cooks.distance' gives only the Cook's distances (as cooks_distance), 'dfbetas' only the DFBETAS (as dfbetas) and 'rstudent' only the deleted residuals (as rstudent). Any other value (the default is 'all') gives the full result.

'all'
progbar bool

Print a progress bar to stderr while the studies are left out in turn (default False); no bar is shown with measure='cooks.distance' or 'rstudent'.

False

Returns:

Type Description
InfluenceResult | Series | DataFrame | ResidualResult

By default an InfluenceResult with one entry per study; its inf property is the influence table

InfluenceResult | Series | DataFrame | ResidualResult

(rstudent, dffits, cook.d, cov.r, tau2.del, QE.del, hat, weight and inf, which marks influential studies

InfluenceResult | Series | DataFrame | ResidualResult

with '*') and dfbs the DFBETAS. With measure set: a Series of Cook's distances, a DataFrame of DFBETAS, or a

InfluenceResult | Series | DataFrame | ResidualResult

Raises:

Type Description
ArgumentError

the model is not a fitted model.

InputError

an argument or the data is invalid.

NotSupportedError

the model was passed through robust.

Metafor reference

influence.rma.uni

influence_rma_mv

influence_rma_mv(
    model: RMAMVResult, *args: Any, **kwargs: Any
) -> InfluenceResult

Not available: metafor has no influence method for rma.mv fits (use cooks_distance and relatives).

Parameters:

Name Type Description Default
model RMAMVResult

A model fitted by rma_mv.

required
*args Any

Ignored.

()
**kwargs Any

Ignored.

{}

Returns:

Type Description
InfluenceResult

Nothing; the function always raises.

Raises:

Type Description
NotSupportedError

always, as in metafor.

cooks_distance

cooks_distance(
    model: Any, *args: Any, **kwargs: Any
) -> Series

Cook's distances of the studies (or clusters) of a fitted model.

This is a single-dispatch function: the implementation is chosen from the class of model (see cooks_rma_mv for rma_mv fits). The rma_uni implementation computes them as part of influence.

Parameters:

Name Type Description Default
model Any

A fitted model object.

required
*args Any

Positional arguments passed to the implementation chosen by the class of model.

()
**kwargs Any

Keyword arguments passed to the implementation chosen by the class of model. For an rma_uni fit these are btt (0-based coefficient indices the distances refer to; default all), na_action ('omit', 'exclude', 'pass' or 'fail') and progbar (print a progress bar).

{}

Returns:

Type Description
Series

A Series of Cook's distances indexed by study label (named cook.d).

Raises:

Type Description
ArgumentError

an argument has the wrong type or is not accepted.

Metafor reference

influence.rma.uni

cooks_rma_mv

cooks_rma_mv(
    model: RMAMVResult,
    progbar: bool = False,
    cluster: str | ArrayLike | None = None,
    reestimate: bool = True,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    LB: bool = False,
    *,
    btt: int | Sequence[int] | str | None = None,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> Series

Cook's distance of each observation, or of each cluster (metafor's cooks.distance.rma.mv).

cluster (a column of the data or a vector for the rows of the original data) deletes whole clusters; the result is then indexed by the sorted cluster ids. btt (0-based) selects the coefficients the distance refers to. With reestimate=False the variance components are not re-estimated in the refits. Cook's distance is the Mahalanobis distance between the predicted values with and without the case (Viechtbauer & Cheung, 2010, doi:10.1002/jrsm.11).

Parameters:

Name Type Description Default
model RMAMVResult

A model fitted by rma_mv (also one passed through robust).

required
progbar bool

Print a progress bar to stderr while the refits are made (default False).

False
cluster str | ArrayLike | None

Clustering variable: a column name of the data the model was fitted to, or a vector with one value per row of that data (before subsetting and removal of rows with missing values, which are applied to it automatically). Whole clusters are then deleted in turn. None (the default) deletes each observation in turn.

None
reestimate bool

Re-estimate the variance and correlation components after each deletion (default True). With False they stay at the full-model values, which is faster and only approximate.

True
parallel Literal['no', 'snow', 'multicore']

'no' (the default), 'snow' or 'multicore'; run the refits in a process pool (see ncpus).

'no'
ncpus int

Number of worker processes (default 1; a value above 1 turns parallel processing on).

1
cl Executor | None

An executor to run the refits on, instead of one created for the call.

None
LB bool

metafor reads this undocumented extra argument to use load-balanced scheduling with parallel='snow'; accepted here and ignored.

False
btt int | Sequence[int] | str | None

The coefficients the distances refer to, as 0-based indices (or a regular expression matched against the coefficient names). None (the default) uses all coefficients. metafor takes this as an undocumented extra argument.

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

How observations dropped for missing values are handled: 'omit' (the default; no entry for them), 'exclude' or 'pass' (an entry of NaN for each) or 'fail' (raise an error).

'omit'

Returns:

Type Description
Series

The Cook's distances, a Series indexed by observation label, or by the sorted cluster ids when cluster is given. A case whose

Series

refit fails gets NaN.

Raises:

Type Description
InputError

an argument or the data is invalid.

Metafor reference

influence.rma.mv

dfbetas

dfbetas(model: Any, *args: Any, **kwargs: Any) -> DataFrame

DFBETAS of the studies (or clusters) of a fitted model.

This is a single-dispatch function: the implementation is chosen from the class of model (see dfbetas_rma_mv for rma_mv fits). The rma_uni implementation computes them as part of influence.

Parameters:

Name Type Description Default
model Any

A fitted model object.

required
*args Any

Positional arguments passed to the implementation chosen by the class of model.

()
**kwargs Any

Keyword arguments passed to the implementation chosen by the class of model. For an rma_uni fit these are na_action ('omit', 'exclude', 'pass' or 'fail') and progbar (print a progress bar).

{}

Returns:

Type Description
DataFrame

A data frame of DFBETAS with one row per study (or cluster) and one column per coefficient.

Raises:

Type Description
ArgumentError

an argument has the wrong type or is not accepted.

Metafor reference

influence.rma.uni

dfbetas_rma_mv

dfbetas_rma_mv(
    model: RMAMVResult,
    progbar: bool = False,
    cluster: str | ArrayLike | None = None,
    reestimate: bool = True,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    LB: bool = False,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> DataFrame

DFBETAS of each observation, or of each cluster (metafor's dfbetas.rma.mv): one column per coefficient.

The change in the coefficients when a cluster is deleted is scaled by the standard errors of the full-data fit with the variance components fixed at the values estimated without the cluster.

Parameters:

Name Type Description Default
model RMAMVResult

A model fitted by rma_mv; not allowed for a model passed through robust.

required
progbar bool

Print a progress bar to stderr while the refits are made (default False).

False
cluster str | ArrayLike | None

Clustering variable: a column name of the data the model was fitted to, or a vector with one value per row of that data (before subsetting and removal of rows with missing values, which are applied to it automatically). Whole clusters are then deleted in turn. None (the default) deletes each observation in turn.

None
reestimate bool

Re-estimate the variance and correlation components after each deletion (default True). With False they stay at the full-model values, which is faster and only approximate.

True
parallel Literal['no', 'snow', 'multicore']

'no' (the default), 'snow' or 'multicore'; run the refits in a process pool (see ncpus).

'no'
ncpus int

Number of worker processes (default 1; a value above 1 turns parallel processing on).

1
cl Executor | None

An executor to run the refits on, instead of one created for the call.

None
LB bool

metafor reads this undocumented extra argument to use load-balanced scheduling with parallel='snow'; accepted here and ignored.

False
na_action Literal['omit', 'exclude', 'pass', 'fail']

How observations dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of missing values for each) or 'fail' (raise an error).

'omit'

Returns:

Type Description
DataFrame

A data frame of DFBETAS with one row per observation (or per sorted cluster id when cluster is given) and one column per

DataFrame

coefficient. A case whose refit fails gets NaN.

Raises:

Type Description
InputError

an argument or the data is invalid.

NotSupportedError

the model was passed through robust.

Metafor reference

influence.rma.mv

InfluenceResult dataclass

InfluenceResult(
    rstudent: FloatArray,
    dffits: FloatArray,
    cook_d: FloatArray,
    cov_r: FloatArray,
    tau2_del: FloatArray,
    QE_del: FloatArray,
    hat: FloatArray,
    weight: FloatArray,
    dfbs_array: FloatArray,
    is_infl: NDArray[bool_],
    slab: tuple[str, ...],
    coef_names: tuple[str, ...],
    tau2: float,
    QE: float,
    k: int,
    p: int,
    m: int,
    digits: int = 4,
    ids: NDArray[intp] | None = None,
    not_na: NDArray[bool_] | None = None,
)

Bases: HtmlRepr

Case-deletion diagnostics: one entry per study.

The inf property is the studies' influence table (columns rstudent, dffits, cook.d, cov.r, tau2.del, QE.del, hat, weight and inf), dfbs the DFBETAS (one column per coefficient) and is_infl marks the studies metafor flags with an asterisk: |DFFITS| > 3 sqrt(p/(k-p)), the lower-tail area of a chi-square distribution with m degrees of freedom cut off by Cook's distance above 50%, hat > 3p/k or any |DFBETAS| > 1.

Attributes:

Name Type Description
rstudent FloatArray

Externally standardised (deleted) residuals.

dffits FloatArray

DFFITS values, the standardised change in the fitted value of each study when it is left out.

cook_d FloatArray

Cook's distances.

cov_r FloatArray

Covariance ratios.

tau2_del FloatArray

Estimates of tau^2 from the fits without each study.

QE_del FloatArray

Test statistics for residual heterogeneity from the fits without each study.

hat FloatArray

Diagonal elements of the hat matrix.

weight FloatArray

Weights of the studies in the model fit, in percent.

dfbs_array FloatArray

DFBETAS as an array with one column per coefficient.

is_infl NDArray[bool_]

Boolean flags for the influential studies.

slab tuple[str, ...]

Study labels, in the order of the rows.

coef_names tuple[str, ...]

Names of the model coefficients.

tau2 float

Estimate of tau^2 of the full model.

QE float

Test statistic for residual heterogeneity of the full model.

k int

Number of studies in the full model.

p int

Number of coefficients in the full model.

m int

Number of coefficients the Cook's distances and covariance ratios refer to (see btt).

digits int

Number of decimals used when the result is printed.

ids NDArray[intp] | None

0-based positions, among the supplied studies, of the studies in the result, if known.

not_na NDArray[bool_] | None

Boolean flags for the studies in the result that were used in the fit (all True with na_action='omit'), if known.

marks property

marks: tuple[str, ...]

'*' for each influential study, '' otherwise.

inf property

inf: DataFrame

The influence table (metafor's inf): rstudent, dffits, cook.d, cov.r, tau2.del, QE.del, hat, weight and inf ('*' for the influential studies), one row per study; attrs holds slab and digits.

dfbs property

dfbs: DataFrame

The DFBETAS (metafor's dfbs), one column per coefficient; attrs holds slab and digits.

to_frame

to_frame() -> DataFrame

The influence table, one row per study.

dfbs_frame

dfbs_frame() -> DataFrame

The DFBETAS, one column per coefficient.

with_digits

with_digits(digits: Any) -> Self

The result printed with digits; every column of the printout is an est column, so a mapping acts through its est element.

ResidualResult dataclass

ResidualResult(
    resid: FloatArray,
    se: FloatArray,
    z: FloatArray,
    slab: tuple[str, ...],
    digits: int = 4,
)

Bases: HtmlRepr

Residuals with standard errors and z-values (metafor's list.rma of rstandard/rstudent).

Attributes:

Name Type Description
resid FloatArray

The residuals, one per study.

se FloatArray

Their standard errors.

z FloatArray

The residuals divided by their standard errors.

slab tuple[str, ...]

Study labels, in the order of the rows.

digits int

Number of decimals used when the result is printed.

__getitem__

__getitem__(index: Any) -> Self

The rows index (metafor's [.list.rma; a NumPy index, 0-based).

ClusterResidualResult dataclass

ClusterResidualResult(
    obs: ResidualResult,
    cluster: tuple[str, ...],
    X2: FloatArray,
    k: FloatArray,
    cluster_slab: tuple[str, ...],
    digits: int = 4,
)

Residuals per observation (obs, with the cluster of each in cluster) and per cluster (metafor's list(obs, cluster)).

X2 is the cluster's (deleted) residuals' quadratic form e' Var(e)^-1 e, k the number of observations in each cluster and cluster_slab the cluster ids (sorted).

Attributes:

Name Type Description
obs ResidualResult

The residuals of the observations, a ResidualResult.

cluster tuple[str, ...]

The cluster of each observation.

X2 FloatArray

Quadratic form of the residuals of each cluster.

k FloatArray

Number of observations in each cluster.

cluster_slab tuple[str, ...]

The cluster ids, sorted; the labels of X2 and k.

digits int

Number of decimals used when the result is printed.

Leave-one-out and cumulative analyses

leave1out

leave1out(
    x: Any, *args: Any, **kwargs: Any
) -> Leave1outResult

Leave-one-out analysis of a fitted model: the model is refitted leaving out each study (or cluster) in turn.

This is a single-dispatch function: the implementation is chosen from the class of x. See leave1out_rma_uni for rma_uni fits and leave1out_fixed_binary for rma_mh and rma_peto fits.

Parameters:

Name Type Description Default
x Any

A fitted model object.

required
*args Any

Positional arguments passed to the implementation chosen by the class of x.

()
**kwargs Any

Keyword arguments passed to the implementation chosen by the class of x.

{}

Returns:

Type Description
Leave1outResult

What the implementation returns, a Leave1outResult.

Raises:

Type Description
ArgumentError

an argument has the wrong type or is not accepted.

Metafor reference

leave1out

leave1out_rma_uni

leave1out_rma_uni(
    x: RMAResult,
    cluster: ArrayLike | str | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    progbar: bool = False,
) -> Leave1outResult

Refit an intercept-only rma.uni model leaving out each study (or each cluster of studies).

transf is applied to the estimates and CI bounds (the integral and mode transformations default to the model's tau2); the standard errors are then NaN. cluster gives one value per study supplied (or a column name in the data the model was fitted to) and leaves out all studies of one cluster at a time. With na_action='exclude'/'pass' (and no cluster) the output has one row per supplied study.

Parameters:

Name Type Description Default
x RMAResult

A model without moderators (an equal- or random-effects model) fitted by rma_uni; not allowed for a model passed through robust.

required
cluster ArrayLike | str | None

Clustering variable: a column name of the data the model was fitted to, or an array with one value per supplied study. All studies of one cluster are left out at a time and the rows are labelled by the sorted cluster ids. None (the default) leaves out one study at a time. Unlike metafor, missing values in cluster are not rejected.

None
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
transf Callable[..., Any] | None

A function applied to the estimates and confidence interval bounds (for example numpy.exp). The integral and mode transformations of metafopy.transf use the tau2 of the model. The standard errors are then NaN. None (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

How studies dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of NaN for each, only without cluster) or 'fail' (which, as in metafor, does not raise an error here and gives the same result as 'omit').

'omit'
progbar bool

Print a progress bar to stderr while the refits are made (default False).

False

Returns:

Type Description
Leave1outResult

A Leave1outResult with one row per left-out study or cluster (labelled -<label>) holding the

Leave1outResult

re-estimated estimate, se, stat (zval, or tval for t, knha and adhoc tests), pval, ci_lb, ci_ub, Q, Qp, I2

Leave1outResult

and H2 (and tau2 for random-effects models). A row is NaN when its refit fails.

Raises:

Type Description
ArgumentError

the model is not a fitted model.

InputError

an argument or the data is invalid, the model has moderators or there is a single study.

NotSupportedError

the model was passed through robust.

Metafor reference

leave1out

leave1out_fixed_binary

leave1out_fixed_binary(
    x: FixedBinaryResult,
    cluster: ArrayLike | str | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | bool | None = None,
    targs: Any = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    progbar: bool = False,
) -> Leave1outResult

Refit the model leaving out each table (or each cluster of tables) in turn (metafor's leave1out for rma.mh and rma.peto).

Parameters:

Name Type Description Default
x FixedBinaryResult

A model fitted by rma_mh or rma_peto.

required
cluster ArrayLike | str | None

Clustering variable: a column name of the data the model was fitted to, or an array with one value per supplied table. All tables of one cluster are left out at a time and the rows are labelled by the sorted cluster ids. None (the default) leaves out one table at a time. Unlike metafor, missing values in cluster are not rejected.

None
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
transf Callable[..., Any] | bool | None

A function applied to the estimates and confidence interval bounds, or True for numpy.exp when the measure is 'OR', 'RR', 'IRR' or 'PETO' (no transformation for other measures). The standard errors are then NaN. None or False (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

How tables with missing counts are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of NaN for each, only without cluster) or 'fail' (raise an error if counts are missing; the R source of metafor's leave1out for these models has no such check).

'omit'
progbar bool

Print a progress bar to stderr while the refits are made (default False).

False

Returns:

Type Description
Leave1outResult

A Leave1outResult with one row per left-out table or cluster (labelled -<label>) holding the

Leave1outResult

re-estimated estimate, se, stat (zval), pval, ci_lb, ci_ub, Q, Qp, I2

Leave1outResult

and H2.

Raises:

Type Description
InputError

na_action is unknown or 'fail' with missing counts, k = 1, or cluster is invalid.

Metafor reference

leave1out

Leave1outResult dataclass

Leave1outResult(
    estimate: FloatArray,
    se: FloatArray,
    stat: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    Q: FloatArray,
    Qp: FloatArray,
    tau2: FloatArray | None,
    I2: FloatArray,
    H2: FloatArray,
    slab: tuple[str, ...],
    stat_name: str = 'zval',
    digits: int = 4,
    digit_map: Mapping[str, int] | None = None,
    transf: bool = False,
    k: FloatArray | None = None,
    order: NDArray[Any] | None = None,
    measure: str = 'GEN',
    level: float = 0.05,
    slab_null: bool = False,
    ids: NDArray[intp] | None = None,
)

One row per left-out study with the re-estimated pooled effect and heterogeneity statistics.

se is NaN when a transformation was applied, as in metafor. tau2 is None for equal/fixed/common-effects models. measure, level (the alpha of the confidence intervals) and slab_null (the studies carry no labels of their own) are used by the plots of cumulative results.

Attributes:

Name Type Description
estimate FloatArray

The pooled estimates, one per left-out study.

se FloatArray

Their standard errors (NaN after a transformation).

stat FloatArray

The test statistics (z or t values) of the estimates.

pval FloatArray

Their p-values.

ci_lb FloatArray

Lower bounds of the confidence intervals.

ci_ub FloatArray

Upper bounds of the confidence intervals.

Q FloatArray

Test statistics for the test of heterogeneity.

Qp FloatArray

Their p-values.

tau2 FloatArray | None

Estimates of tau^2, or None for equal-, fixed- and common-effects models.

I2 FloatArray

Values of I^2.

H2 FloatArray

Values of H^2.

slab tuple[str, ...]

Row labels ('-<study>' for a left-out study).

stat_name str

Name of the test statistic column, 'zval' or 'tval'.

digits int

Number of decimals used when the result is printed.

digit_map Mapping[str, int] | None

Per-quantity decimals when digits was given as a mapping, else None.

transf bool

Whether a transformation was applied.

k FloatArray | None

Number of studies in each fit (cumulative results; None for a leave-one-out result).

order NDArray[Any] | None

Values of the ordering variable (cumulative results; None for a leave-one-out result).

measure str

Effect size measure of the model (set for cumulative results; 'GEN' for a leave-one-out result).

level float

Alpha of the confidence intervals (set for cumulative results; 0.05 for a leave-one-out result).

slab_null bool

Whether the studies carry no labels of their own.

ids NDArray[intp] | None

0-based positions of the studies among those supplied, if known.

zval property

zval: FloatArray

The test statistics of the pooled effects, metafor's zval (tval for the t-based tests, see :attr:stat_name).

tval property

tval: FloatArray

The test statistics of the pooled effects, metafor's tval for the t-based tests (the same array as :attr:zval).

test property

test: str

't' for the t-based tests and 'z' otherwise (metafor stores the model's test, so 'knha' and 'adhoc' read 't' here).

__getitem__

__getitem__(index: Any) -> Self

The rows index (metafor's [.list.rma; a NumPy index, 0-based).

to_frame

to_frame() -> DataFrame

Table with metafor's column names (estimate, se, zval/tval, pval, ci.lb, ...).

with_digits

with_digits(digits: Any) -> Self

The result printed with digits (a number, or a mapping with any of the keys of :data:metafopy.mfopt.DIGIT_KEYS).

cumul

cumul(x: Any, *args: Any, **kwargs: Any) -> CumulResult

Cumulative meta-analysis of a fitted model: the model is fitted to the first i studies for i = 1, ..., k.

This is a single-dispatch function: the implementation is chosen from the class of x. See cumul_rma_uni for rma_uni fits and cumul_fixed_binary for rma_mh and rma_peto fits.

Parameters:

Name Type Description Default
x Any

A fitted model object.

required
*args Any

Positional arguments passed to the implementation chosen by the class of x.

()
**kwargs Any

Keyword arguments passed to the implementation chosen by the class of x.

{}

Returns:

Type Description
CumulResult

What the implementation returns, a CumulResult.

Raises:

Type Description
ArgumentError

an argument has the wrong type or is not accepted.

Metafor reference

cumul

cumul_rma_uni

cumul_rma_uni(
    x: RMAResult,
    order: ArrayLike | str | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    collapse: bool = False,
    *,
    decreasing: bool = False,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    progbar: bool = False,
) -> CumulResult

Fit the intercept-only model to the first i studies for i = 1, ..., k (metafor's cumul.rma.uni).

A cumulative meta-analysis describes the accumulation of evidence as studies are added, typically in chronological order (Chalmers & Lau, 1993, doi:10.1177/096228029300200204; Lau, Schmid & Chalmers, 1995, doi:10.1016/0895-4356(94)00106-Z). Studies dropped for missing values in the fit are skipped. na_action stands for R's options(na.action=), as in metafor (see https://github.com/wviechtb/metafor/blob/master/R/cumul.rma.uni.r).

Parameters:

Name Type Description Default
x RMAResult

A model without moderators (an equal- or random-effects model) fitted by rma_uni; not allowed for a model passed through robust.

required
order ArrayLike | str | None

Variable giving the order in which the studies are added, ascending: a column name of the data the model was fitted to, or an array with one value per supplied study. Studies with a missing value are not added. None (the default) uses the original order and ignores collapse.

None
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
transf Callable[..., Any] | None

A function applied to the estimates and confidence interval bounds (for example numpy.exp). The integral and mode transformations of metafopy.transf use the tau2 of the model. The standard errors are then NaN. None (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
collapse bool

Add studies with the same value of order together instead of one at a time (default False).

False
decreasing bool

Add the studies in descending order of order (default False). metafor takes this as an undocumented extra argument.

False
na_action Literal['omit', 'exclude', 'pass', 'fail']

How studies dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of missing values for each) or 'fail' (raise an error).

'omit'
progbar bool

Print a progress bar to stderr while the refits are made (default False).

False

Returns:

Type Description
CumulResult

A CumulResult with one row per added study (or group of studies) holding the number of studies included k,

CumulResult

the values of order (the 0-based positions of the studies if order is None) and the re-estimated estimate, se,

CumulResult

stat (zval, or tval for t, knha and adhoc tests), pval, ci_lb, ci_ub, Q, Qp, I2 and H2

CumulResult

(and tau2 for random-effects models).

Raises:

Type Description
ArgumentError

the model is not a fitted model.

InputError

an argument or the data is invalid, the model has moderators, or na_action='fail' and values are missing.

NotSupportedError

the model was passed through robust.

Metafor reference

cumul

cumul_fixed_binary

cumul_fixed_binary(
    x: FixedBinaryResult,
    order: ArrayLike | str | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | bool | None = None,
    targs: Any = None,
    collapse: bool = False,
    *,
    decreasing: bool = False,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
    progbar: bool = False,
) -> CumulResult

Fit the model to the first i tables for i = 1, ..., k (metafor's cumul for rma.mh and rma.peto).

Tables with missing counts are skipped.

Parameters:

Name Type Description Default
x FixedBinaryResult

A model fitted by rma_mh or rma_peto.

required
order ArrayLike | str | None

Variable giving the order in which the tables are added, ascending: a column name of the data the model was fitted to, or an array with one value per supplied table. None (the default) uses the original order and ignores collapse.

None
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
transf Callable[..., Any] | bool | None

A function applied to the estimates and confidence interval bounds, or True for numpy.exp when the measure is 'OR', 'RR', 'IRR' or 'PETO' (no transformation for other measures). The standard errors are then NaN. None or False (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
collapse bool

Add tables with the same value of order together instead of one at a time (default False).

False
decreasing bool

Add the tables in descending order of order (default False). metafor takes this as an undocumented extra argument.

False
na_action Literal['omit', 'exclude', 'pass', 'fail']

How tables with missing counts are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of missing values for each) or 'fail' (raise an error).

'omit'
progbar bool

Print a progress bar to stderr while the refits are made (default False).

False

Returns:

Type Description
CumulResult

A CumulResult with one row per added table (or group of tables) holding the number of tables included k,

CumulResult

the values of order (the 0-based positions of the tables if order is None) and the re-estimated estimate, se,

CumulResult

stat (zval), pval, ci_lb, ci_ub, Q, Qp, I2 and H2.

Raises:

Type Description
InputError

na_action is unknown, order is invalid or tables are missing and na_action='fail'.

Metafor reference

cumul

CumulResult dataclass

CumulResult(
    estimate: FloatArray,
    se: FloatArray,
    stat: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    Q: FloatArray,
    Qp: FloatArray,
    tau2: FloatArray | None,
    I2: FloatArray,
    H2: FloatArray,
    slab: tuple[str, ...],
    stat_name: str = 'zval',
    digits: int = 4,
    digit_map: Mapping[str, int] | None = None,
    transf: bool = False,
    k: FloatArray | None = None,
    order: NDArray[Any] | None = None,
    measure: str = 'GEN',
    level: float = 0.05,
    slab_null: bool = False,
    ids: NDArray[intp] | None = None,
)

Bases: Leave1outResult

Cumulative meta-analysis results (Leave1outResult plus k and the ordering variable).

Each row holds the result of the model fitted to the studies added so far, in the order the studies were added. k is the number of studies included and order the values of the ordering variable. The other attributes are those of Leave1outResult.

Random effects and GOSH

blup

blup(res: Any, *args: Any, **kwargs: Any) -> BlupResult

Best linear unbiased predictions (BLUPs) of the true effects for a fitted model.

This is a single-dispatch function: the implementation is chosen from the class of res. See blup_rma_uni for rma_uni fits (and blup_rma_ls for location-scale models).

Parameters:

Name Type Description Default
res Any

A fitted model object.

required
*args Any

Positional arguments passed to the implementation chosen by the class of res.

()
**kwargs Any

Keyword arguments passed to the implementation chosen by the class of res.

{}

Returns:

Type Description
BlupResult

What the implementation returns, a BlupResult.

Raises:

Type Description
ArgumentError

an argument has the wrong type or is not accepted.

Metafor reference

blup

blup_rma_uni

blup_rma_uni(
    res: RMAResult,
    level: float | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> BlupResult

BLUPs of the true effects of an rma.uni fit (metafor's blup.rma.uni).

The prediction for study i shrinks its observed effect towards the model's fitted value (the empirical Bayes estimate of its true effect). Prediction intervals use a normal distribution, or a t-distribution with the model's ddf degrees of freedom (k - p unless dfs was given) when the model was fitted with a t, knha or adhoc test. For equal- and fixed-effects models the BLUPs equal the fitted values. na_action plays the role of R's options(na.action=).

Parameters:

Name Type Description Default
res RMAResult

A model fitted by rma_uni.

required
level float | None

Level of the prediction intervals in percent (e.g. 95), or a value below 1 read as in metafor (0.95 and 0.05 both give 95 percent). None (the default) uses the level of the model.

None
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
transf Callable[..., Any] | None

A function applied to the predicted values and interval bounds (for example numpy.exp); the standard errors are then NaN. None (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

How studies dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of NaN for each, so there is one row per supplied study) or 'fail' (raise an error).

'omit'

Returns:

Type Description
BlupResult

A BlupResult with the predictions pred, standard errors se and prediction interval bounds pi_lb

BlupResult

and pi_ub, one entry per study.

Raises:

Type Description
InputError

the model has user-defined weights, na_action is unknown or values are missing with na_action='fail'.

Metafor reference

blup

blup_rma_glmm

blup_rma_glmm(
    res: GLMMResult, *args: Any, **kwargs: Any
) -> BlupResult

Not available: metafor has no blup method for rma.glmm objects (only blup.rma.uni).

Parameters:

Name Type Description Default
res GLMMResult

A model fitted by rma_glmm.

required
*args Any

Ignored.

()
**kwargs Any

Ignored.

{}

Returns:

Type Description
BlupResult

Nothing; the function always raises.

Raises:

Type Description
NotSupportedError

always, as in metafor ("no applicable method for 'blup' applied to an object of class c('rma.glmm', 'rma')").

blup_rma_ls

blup_rma_ls(
    res: RMALSResult,
    level: float | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> BlupResult

BLUPs of the true effects of a location-scale fit (metafor's blup.rma.uni for rma.ls objects).

The arguments are those of blup_rma_uni; the shrinkage uses the study-specific tau^2 of the scale model.

Parameters:

Name Type Description Default
res RMALSResult

A location-scale model fitted by rma_uni with scale.

required
level float | None

Level of the prediction intervals in percent (e.g. 95), or a value below 1 read as in metafor (0.95 and 0.05 both give 95 percent). None (the default) uses the level of the model.

None
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
transf Callable[..., Any] | None

A function applied to the predicted values and interval bounds (for example numpy.exp); the standard errors are then NaN. None (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

How studies dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of NaN for each, so there is one row per supplied study) or 'fail' (raise an error).

'omit'

Returns:

Type Description
BlupResult

A BlupResult with the predictions pred, standard errors se and prediction interval bounds pi_lb

BlupResult

and pi_ub, one entry per study.

Raises:

Type Description
InputError

the model has user-defined weights, na_action is unknown or values are missing with na_action='fail'.

Metafor reference

blup

BlupResult dataclass

BlupResult(
    pred: FloatArray,
    se: FloatArray,
    pi_lb: FloatArray,
    pi_ub: FloatArray,
    slab: tuple[str, ...],
    digits: int = 4,
    transf: bool = False,
)

Predicted values with standard errors and prediction intervals (metafor's list.rma).

se is NaN when a transformation was applied, as in metafor.

Attributes:

Name Type Description
pred FloatArray

The predicted values (BLUPs of the true effects, or predicted random effects), one per study.

se FloatArray

Their standard errors.

pi_lb FloatArray

Lower bounds of the prediction intervals.

pi_ub FloatArray

Upper bounds of the prediction intervals.

slab tuple[str, ...]

Study labels, in the order of the rows.

digits int

Number of decimals used when the result is printed.

transf bool

Whether a transformation was applied to the predictions.

__getitem__

__getitem__(index: Any) -> Self

The rows index (metafor's [.list.rma; a NumPy index, 0-based).

ranef

ranef(res: Any, *args: Any, **kwargs: Any) -> RanefResult

Best linear unbiased predictions (BLUPs) of the random effects for a fitted model.

This is a single-dispatch function: the implementation is chosen from the class of res. See ranef_rma_uni for rma_uni fits, ranef_rma_ls for location-scale models and ranef_rma_mv for rma_mv fits.

Parameters:

Name Type Description Default
res Any

A fitted model object.

required
*args Any

Positional arguments passed to the implementation chosen by the class of res.

()
**kwargs Any

Keyword arguments passed to the implementation chosen by the class of res.

{}

Returns:

Type Description
RanefResult

What the implementation returns: a RanefResult (or a dict of data frames for rma_mv fits).

Raises:

Type Description
ArgumentError

an argument has the wrong type or is not accepted.

Metafor reference

ranef

ranef_rma_uni

ranef_rma_uni(
    res: RMAResult,
    level: float | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> RanefResult

BLUPs of the random effects of an rma.uni fit (metafor's ranef.rma.uni).

The prediction for study i is the BLUP of its deviation from the model's fitted value (the random effect). For equal- and fixed-effects models all random effects are 0. The arguments are those of blup_rma_uni.

Parameters:

Name Type Description Default
res RMAResult

A model fitted by rma_uni.

required
level float | None

Level of the prediction intervals in percent (e.g. 95), or a value below 1 read as in metafor (0.95 and 0.05 both give 95 percent). None (the default) uses the level of the model.

None
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
transf Callable[..., Any] | None

A function applied to the predicted values and interval bounds (for example numpy.exp); the standard errors are then NaN. None (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

How studies dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of NaN for each, so there is one row per supplied study) or 'fail' (raise an error).

'omit'

Returns:

Type Description
RanefResult

A RanefResult with the predicted random effects pred, standard errors se and prediction interval

RanefResult

bounds pi_lb and pi_ub, one entry per study.

Raises:

Type Description
InputError

the model has user-defined weights, na_action is unknown or values are missing with na_action='fail'.

Metafor reference

ranef

ranef_rma_glmm

ranef_rma_glmm(
    res: GLMMResult, *args: Any, **kwargs: Any
) -> RanefResult

Not available: metafor has no ranef method for rma.glmm objects (only ranef.rma.uni and ranef.rma.mv).

Parameters:

Name Type Description Default
res GLMMResult

A model fitted by rma_glmm.

required
*args Any

Ignored.

()
**kwargs Any

Ignored.

{}

Returns:

Type Description
RanefResult

Nothing; the function always raises.

Raises:

Type Description
NotSupportedError

always, as in metafor ("no applicable method for 'ranef' applied to an object of class c('rma.glmm', 'rma')").

ranef_rma_ls

ranef_rma_ls(
    res: RMALSResult,
    level: float | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> RanefResult

BLUPs of the random effects of a location-scale fit (metafor's ranef.rma.uni for rma.ls objects).

The arguments are those of blup_rma_uni.

Parameters:

Name Type Description Default
res RMALSResult

A location-scale model fitted by rma_uni with scale.

required
level float | None

Level of the prediction intervals in percent (e.g. 95), or a value below 1 read as in metafor (0.95 and 0.05 both give 95 percent). None (the default) uses the level of the model.

None
digits int | None

Number of decimals used when the result is printed. None uses the digits option, else the digits of the model.

None
transf Callable[..., Any] | None

A function applied to the predicted values and interval bounds (for example numpy.exp); the standard errors are then NaN. None (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

How studies dropped for missing values are handled: 'omit' (the default; no row for them), 'exclude' or 'pass' (a row of NaN for each, so there is one row per supplied study) or 'fail' (raise an error).

'omit'

Returns:

Type Description
RanefResult

A RanefResult with the predicted random effects pred, standard errors se and prediction interval

RanefResult

bounds pi_lb and pi_ub, one entry per study.

Raises:

Type Description
InputError

the model has user-defined weights, na_action is unknown or values are missing with na_action='fail'.

Metafor reference

ranef

ranef_rma_mv

ranef_rma_mv(
    object: RMAMVResult,
    level: float | None = None,
    digits: int | None = None,
    transf: Callable[..., Any] | None = None,
    targs: Any = None,
    verbose: bool = False,
    *,
    expand: bool = False,
    vcov: bool = False,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> dict[str, Any] | DataFrame | None

BLUPs of the random effects of an rma.mv fit: a dict with one data frame (intrcpt, se, pi.lb, pi.ub) per term.

The ~ 1 | id terms are keyed by their grouping variables (s_names), the ~ inner | outer terms by their formulas ('~inner | outer'), as in metafor. level sets the level of the prediction intervals; transf (with targs) is applied to the predictions and interval bounds and drops the se column. expand=True gives the ~ 1 | id terms one row per observation; vcov=True returns {'pred': ..., 'vcov': ...} with the prediction variance-covariance matrices. For struct='GEN'/'GDIAG' metafor returns (only) the matrix of BLUPs of the first ~ inner | outer term, without standard errors; so does this function. digits and verbose have no effect (digits is not used by metafor either; the progress messages are not reproduced). None for models without random effects.

Parameters:

Name Type Description Default
object RMAMVResult

A model fitted by rma_mv.

required
level float | None

Level of the prediction intervals in percent (e.g. 95), or a value below 1 read as in metafor (0.95 and 0.05 both give 95 percent). None (the default) uses the level of the model.

None
digits int | None

Accepted for compatibility; it has no effect.

None
transf Callable[..., Any] | None

A function applied to the predictions and interval bounds (for example numpy.exp); the se column is then dropped. None (the default) applies no transformation.

None
targs Any

Extra argument passed to transf as transf(x, targs). None (the default) calls transf(x).

None
verbose bool

Accepted for compatibility; it has no effect.

False
expand bool

Give the ~ 1 | id terms one row per observation instead of one per level (default False).

False
vcov bool

Also return the variance-covariance matrices of the predictions (default False).

False
na_action Literal['omit', 'exclude', 'pass', 'fail']

How observations dropped for missing values are handled: 'omit' (the default; the ~ 1 | id terms have a row for each level that occurs in the observations used), 'exclude' or 'pass' (those terms also have a row of NaN for each level that only occurs in dropped observations) or 'fail' (raise an error if observations were dropped; metafor's ranef.rma.mv has no such check). It has no effect on the ~ inner | outer terms.

'omit'

Returns:

Type Description
dict[str, Any] | DataFrame | None

A dict (named list) with one data frame per random-effects term, with columns intrcpt (the predicted random effect), se, pi.lb and

dict[str, Any] | DataFrame | None

pi.ub. With vcov=True a dict {'pred': ..., 'vcov': ...} whose vcov holds the matrices by term. For struct='GEN' or

dict[str, Any] | DataFrame | None

'GDIAG' a single data frame of BLUPs without standard errors. None for a model without random effects.

Raises:

Type Description
InputError

the model has user-defined weights, na_action is unknown or 'fail' with missing values.

InternalError

a term of a non-spatial structure has no inner factor.

Metafor reference

ranef

RanefResult dataclass

RanefResult(
    pred: FloatArray,
    se: FloatArray,
    pi_lb: FloatArray,
    pi_ub: FloatArray,
    slab: tuple[str, ...],
    digits: int = 4,
    transf: bool = False,
)

Bases: BlupResult

Predicted random effects with standard errors and prediction intervals.

The attributes are those of BlupResult: pred, se, pi_lb, pi_ub, slab, digits and transf.

gosh

gosh(x: Any, *args: Any, **kwargs: Any) -> GoshResult

GOSH (graphical display of study heterogeneity) analysis of a fitted model.

This is a single-dispatch function: the implementation is chosen from the class of x. See gosh_rma_uni for rma_uni fits. Fits of rma_mh and rma_peto are also supported (as in metafor), with the same arguments as gosh_rma_uni; the subsets then have one or more tables and the result has the column estimate.

Parameters:

Name Type Description Default
x Any

A fitted model object.

required
*args Any

Positional arguments passed to the implementation chosen by the class of x.

()
**kwargs Any

Keyword arguments passed to the implementation chosen by the class of x.

{}

Returns:

Type Description
GoshResult

What the implementation returns, a GoshResult.

Raises:

Type Description
ArgumentError

an argument has the wrong type or is not accepted.

NotSupportedError

the model is of a class metafor has no GOSH analysis for (rma.ls, rma.glmm, rma.mv, selection models, robust.rma and others).

Metafor reference

gosh

gosh_rma_uni

gosh_rma_uni(
    x: RMAResult,
    subsets: int | None = None,
    *,
    seed: int | None = None,
    rng: RRandom | None = None,
    progbar: bool = False,
    parallel: Literal['no', 'snow', 'multicore'] = 'no',
    ncpus: int = 1,
    cl: Executor | None = None,
    LB: bool = False,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> GoshResult

Fit the model to subsets of the studies (metafor's gosh.rma).

Olkin, Dahabreh & Trikalinos (2012, doi:10.1002/jrsm.1053) proposed examining the pooled estimate and the heterogeneity statistics of the model fitted to all subsets of the studies; Viechtbauer (2021) generalised this to models with moderators. By default all subsets (with at least p studies, p being the number of coefficients) are used if there are at most 10**6 of them, otherwise 10**6 random subsets are drawn. The subsets are drawn before the fits, so the result equals that of a serial run.

Parameters:

Name Type Description Default
x RMAResult

A model fitted by rma_uni, with or without moderators; not allowed for a model passed through robust, or for location-scale and selection models.

required
subsets int | None

Number of subsets to use. None (the default) uses all subsets if there are at most 10**6, else 10**6 random ones. If it is at least the number of possible subsets, all subsets are used. Must be 2 or more.

None
seed int | None

Seed of the R-compatible random number generator used to draw random subsets, so that gosh(res, seed=s) draws the same subset sizes and study indices as R's set.seed(s). None uses the global generator (see set_seed). Only used when random subsets are drawn.

None
rng RRandom | None

An R-compatible generator to draw the random subsets from, instead of seed or the global generator.

None
progbar bool

Print a progress bar (per block of subsets) to stderr (default False; metafor's default is TRUE).

False
parallel Literal['no', 'snow', 'multicore']

'no' (the default), 'snow' or 'multicore'; fit the subsets in a process pool (see ncpus).

'no'
ncpus int

Number of worker processes (default 1; a value above 1 turns parallel processing on).

1
cl Executor | None

An executor to fit the subsets on, instead of one created for the call.

None
LB bool

metafor reads this undocumented extra argument to use load-balanced scheduling with parallel='snow'; accepted here and ignored.

False
na_action Literal['omit', 'exclude', 'pass', 'fail']

Stands for R's options(na.action=); metafor only checks that it is one of 'omit' (the default), 'exclude', 'pass' or 'fail', and so does this function.

'omit'

Returns:

Type Description
GoshResult

A GoshResult. Its res data frame has one row per subset (sorted by the number of studies) with the columns

GoshResult

k, QE, I2, H2, tau2, tau and the coefficient estimates (estimate for a model without moderators);

GoshResult

incl is the matrix of inclusion indicators.

Raises:

Type Description
ArgumentError

x is not a fitted model.

InputError

an argument or the data is invalid.

NotSupportedError

the model is of a class that is not supported (see x).

Metafor reference

gosh

GoshResult dataclass

GoshResult(
    res: DataFrame,
    incl: NDArray[bool_],
    fit: NDArray[bool_],
    k: int,
    int_only: bool,
    method: str,
    measure: str,
    digits: int = 4,
)

Statistics of the model fitted to each subset of studies.

res has one row per subset (sorted by the number of studies k) with the columns k, QE, I2, H2, tau2, tau and the coefficient estimates; incl is the corresponding matrix of inclusion indicators, fit marks successful fits.

Attributes:

Name Type Description
res DataFrame

Data frame with one row per subset of studies.

incl NDArray[bool_]

Boolean matrix with one row per subset and one column per study; true where the study is in the subset.

fit NDArray[bool_]

Boolean flags for the subsets whose model fit succeeded.

k int

Number of studies of the model.

int_only bool

Whether the model has no moderators.

method str

The tau^2 estimator of the model.

measure str

The effect size measure of the model.

digits int

Number of decimals used when the result is printed.

Sampling variance-covariance matrices

vcalc

vcalc(
    vi: ArrayLike | str | None = None,
    cluster: ArrayLike | str | None = None,
    subgroup: ArrayLike | str | None = None,
    obs: ArrayLike | str | None = None,
    type: ArrayLike | str | None = None,
    time1: ArrayLike | str | None = None,
    time2: ArrayLike | str | None = None,
    grp1: ArrayLike | str | None = None,
    grp2: ArrayLike | str | None = None,
    w1: ArrayLike | str | None = None,
    w2: ArrayLike | str | None = None,
    data: DataFrame | Mapping[str, Any] | None = None,
    rho: float
    | ArrayLike
    | DataFrame
    | Sequence[Any]
    | None = None,
    phi: float | None = None,
    rvars: Sequence[str | int] | slice | None = None,
    checkpd: bool = True,
    nearpd: bool = False,
    sparse: bool = False,
    retdat: bool = False,
) -> NDArray[float64] | csr_array | DataFrame

Variance-covariance matrix of dependent estimates, block diagonal over cluster (metafor's vcalc).

Rows with the same cluster (and subgroup) may be dependent, rows of different clusters are independent. Within a cluster the correlation of two estimates is built from rho (estimates of the same or of different constructs), from phi and the time points time1/time2 (an autoregressive structure), and from the groups grp1/grp2 with sizes w1/w2 for estimates that are contrasts between two conditions and so share a condition. The matrix can be used as the V argument of rma_mv. With rvars the correlation matrices of the clusters are read from columns of data instead.

Differences from R: metafor's undocumented nearPD alias of nearpd is not accepted; in rvars mode the matrix of a cluster is placed at that cluster's rows even when the rows of a cluster are not contiguous (R places the blocks in order of first appearance, which misaligns the matrix in that case).

Parameters:

Name Type Description Default
vi ArrayLike | str | None

Sampling variances of the estimates, as an array or the name of a column of data. Required. A single value is repeated for as many rows as cluster has.

None
cluster ArrayLike | str | None

Clustering variable (for example the study), an array or a column name. Required, without missing values. Rows with the same value may be dependent.

None
subgroup ArrayLike | str | None

Variable distinguishing independent subgroups within clusters (no overlap of subjects), an array or a column name. Rows of different subgroups are independent even in the same cluster. None for no subgroups.

None
obs ArrayLike | str | None

Variable distinguishing different estimates of the same construct or response variable (for example several scales for depression), an array or a column name. Needs rho.

None
type ArrayLike | str | None

Variable distinguishing different types of constructs or response variables, an array or a column name. Needs rho.

None
time1 ArrayLike | str | None

Numeric time points at which the estimates were obtained (in the first condition for contrasts), an array or a column name. Needs phi.

None
time2 ArrayLike | str | None

Numeric time points in the second condition for contrasts between two conditions, an array or a column name.

None
grp1 ArrayLike | str | None

Group of the first condition for estimates that are contrasts between two conditions (for example [2, 3] with grp2=[1, 1] for two treatments versus one control), an array or a column name. Give grp1 alone or with grp2.

None
grp2 ArrayLike | str | None

Group of the second condition, an array or a column name.

None
w1 ArrayLike | str | None

Size of the group of the first condition (or more generally its inverse-sampling-variance weight), numeric, an array or a column name. Default: equal group sizes, which implies a correlation of 0.5 between contrasts that share a condition.

None
w2 ArrayLike | str | None

Size (weight) of the group of the second condition, numeric, an array or a column name.

None
data DataFrame | Mapping[str, Any] | None

Data frame (or mapping of columns) holding the variables named above.

None
rho float | ArrayLike | DataFrame | Sequence[Any] | None

Correlation of the sampling errors of estimates measured concurrently. A scalar, or a correlation matrix as a data frame whose row and column labels are the unique values of obs (or of type). With both obs and type a pair: the first element (a scalar or matrix) is the within-construct correlation among the obs values, the second the between-construct correlation among the type values.

None
phi float | None

Autocorrelation of the sampling errors of two estimates that differ by one unit of time1.

None
rvars Sequence[str | int] | slice | None

Columns of data that hold the correlation matrices of the clusters: names or 0-based positions, or a slice of names (slice('r1', 'r4') for R's r1:r4). The first k_i columns hold the lower triangle of the matrix of the i-th cluster (k_i rows); there must be as many columns as the largest cluster has rows. When given, all variable arguments except vi, cluster and subgroup are ignored. Needs data.

None
checkpd bool

Warn about clusters whose variance-covariance matrix is not positive definite (default True).

True
nearpd bool

Replace such matrices by the nearest correlation matrix (Matrix::nearPD(corr=TRUE) in R). Use with care (default False).

False
sparse bool

Return a sparse matrix (default False).

False
retdat bool

Return a data frame of the variables used with the matrix appended in columns V.1, V.2, ... instead of the matrix (default False; metafor takes this as an undocumented extra argument).

False

Returns:

Type Description
NDArray[float64] | csr_array | DataFrame

The k x k variance-covariance matrix, with k the length of vi: a dense array that prints like metafor's vcovmat

NDArray[float64] | csr_array | DataFrame

(VCovMat), a scipy.sparse.csr_array if sparse=True, or with retdat=True a data frame of

NDArray[float64] | csr_array | DataFrame

the variables used with the matrix in the columns V.1, V.2, ....

Raises:

Type Description
InputError

an argument or the data is invalid (R stops with an error here).

NotFoundError

a named column is not in data.

ArgumentError

rho has an unsupported type.

InternalError

vi, cluster, subgroup or the frame is missing after the checks above.

Metafor reference

vcalc

rcalc

rcalc(
    x: str
    | (NDArray[float64] | DataFrame)
    | Sequence[NDArray[float64] | DataFrame]
    | Mapping[str, NDArray[float64] | DataFrame],
    ni: ArrayLike | str | None | float = None,
    data: DataFrame | Mapping[str, Any] | None = None,
    rtoz: bool = False,
    nfun: str | Callable[[NDArray[float64]], float] = 'min',
    sparse: bool = False,
    upper: bool = False,
    simplify: bool = True,
    *,
    rowid: Sequence[str] | None = None,
    vnames: Sequence[str] | None = None,
    noid: bool | None = None,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> RCalcResult | dict[str, RCalcResult]

Variance-covariance matrix of correlation coefficients from the same samples (metafor's rcalc).

Correlations computed from the same sample are not independent. Equations for the sampling covariances can be found in Steiger (1980, doi:10.1037/0033-2909.87.2.245) and Olkin and Finn (1990, doi:10.1037/0033-2909.108.2.330); for raw correlations the denominator is ni - 1 (as in metafor), for r-to-z transformed ones ni - 3. The data and the matrix can be passed on to rma_mv. As in R, the study identifier in dat consists of strings (the names of the list, or the ids converted to character).

Parameters:

Name Type Description Default
x str | (NDArray[float64] | DataFrame) | Sequence[NDArray[float64] | DataFrame] | Mapping[str, NDArray[float64] | DataFrame]

A formula string such as 'ri ~ var1 + var2 | study' (the study part may be left out for a single study), naming the correlations, the two variables of each and the study in data; or a correlation matrix; or a list or dict of correlation matrices. Matrices are arrays or data frames whose column labels name the variables (x1, x2, ... if unnamed).

required
ni ArrayLike | str | None | float

Sample sizes the correlations are based on: for a formula, a column name of data or an array; for a matrix, the (common) sample size; for a list of matrices, one sample size per matrix. Required.

None
data DataFrame | Mapping[str, Any] | None

Data frame (or mapping of columns) holding the variables of the formula (and ni). Required for a formula.

None
rtoz bool

Transform the correlations with Fisher's r-to-z transformation and compute the matrix for the transformed values (default False).

False
nfun str | Callable[[NDArray[float64]], float]

How the common sample size within a study is computed when it differs between correlations: 'min' (the default; conservative), 'harmonic' (harmonic mean) or 'mean', an unambiguous prefix of these, or a function of the array of the sample sizes of a study returning a single value.

'min'
sparse bool

Return the matrix as a sparse matrix (default False; only with a list of matrices or a formula does this give a sparse V).

False
upper bool

For matrices, use the upper instead of the lower triangle (default False; metafor takes this as an undocumented extra argument).

False
simplify bool

For a list of matrices, combine the results into one (default True); with False a dict of one result per matrix (metafor takes this as an undocumented extra argument).

True
rowid Sequence[str] | None

For a list of matrices with simplify=True: values of 'id.var1.var2' giving the order of the rows of dat and V (metafor passes this on internally for a formula).

None
vnames Sequence[str] | None

For a list of matrices with simplify=True: four names for the columns of dat.

None
noid bool | None

For a list of matrices with simplify=True: drop the study identifier from dat (default False).

None
na_action Literal['omit', 'exclude', 'pass', 'fail']

Stands for R's options(na.action=); an unknown value raises, the known ones ('omit' (the default), 'exclude', 'pass' and 'fail') give the same result (metafor sets na.pass while it computes).

'omit'

Returns:

Type Description
RCalcResult | dict[str, RCalcResult]

An RCalcResult with the data dat (one row per correlation) and the block diagonal variance-covariance matrix

RCalcResult | dict[str, RCalcResult]

V. A covariance is NaN when a correlation it needs is missing, and nothing is computed for studies with a common sample size

RCalcResult | dict[str, RCalcResult]

below 5. With simplify=False and a list of matrices, a dict of one such result per matrix.

Raises:

Type Description
ArgumentError

x is not a formula, a matrix or a list of matrices.

InputError

an argument or the data is invalid (R stops with an error here).

InternalError

a variable of the formula is missing after the checks above.

NotFoundError

a variable of the formula is not in data.

Metafor reference

rcalc

RCalcResult dataclass

RCalcResult(
    dat: DataFrame | None, V: FloatArray | csr_array | None
)

The pair of dat (one row per correlation) and V (their variance-covariance matrix) that rcalc returns.

Both are None for a single matrix of dimension 1 x 1 or smaller. V is dense, except that sparse=True with a list of matrices (or a formula) gives a scipy.sparse.csr_array.

Attributes:

Name Type Description
dat DataFrame | None

Data frame with one row per correlation, with the columns var1 and var2 (the two variable identifiers), var1.var2 (a variable pair identifier), yi (the correlation, possibly r-to-z transformed) and ni (the common sample size). For a list of matrices (and so for a formula) it has the study identifier as its first column (id, or the name of the study variable of a formula).

V FloatArray | csr_array | None

The block diagonal variance-covariance matrix of the correlations; its row and column names are in dat['var1.var2'].

bldiag

bldiag(
    *mlist: ArrayLike
    | DataFrame
    | sparray
    | spmatrix
    | Mapping[
        Any, ArrayLike | DataFrame | sparray | spmatrix
    ],
    order: ArrayLike | None = None,
    order_is_permutation: bool = False,
) -> NDArray[float64]

Block diagonal matrix from matrices (metafor's bldiag).

Accepts matrices (arrays, data frames or scipy sparse arrays), vectors and scalars (turned into diagonal matrices, so bldiag(numpy.ones((3, 3)), 2) works) or a single list, tuple or dict (R's named list) of these. Matrices with zero rows or columns are dropped; if none are left the result is 0 x 0.

order is the clustering variable according to which the rows and columns of the result are reordered back to the original order of the data (R: order=cluster). With order_is_permutation=True it is instead the permutation itself (R: order=order(cluster)).

Parameters:

Name Type Description Default
*mlist ArrayLike | DataFrame | sparray | spmatrix | Mapping[Any, ArrayLike | DataFrame | sparray | spmatrix]

The matrices to put on the diagonal: arrays, data frames or scipy sparse arrays, vectors and scalars (made diagonal), or a single list, tuple or dict of these.

()
order ArrayLike | None

Clustering variable (one value per row of the result) used to reorder the rows and columns of a square result back to the original order of the data, for blocks that were built in the order of the sorted clusters. None (the default) keeps the order of the blocks.

None
order_is_permutation bool

Treat order as the permutation itself (R's order=order(cluster)) rather than as a clustering variable (default False).

False

Returns:

Type Description
NDArray[float64]

The block diagonal matrix, a dense array (0 x 0 if no non-empty matrices were given). Unlike metafor, which gives the result the class

NDArray[float64]

vcovmat when an element has it, the result is a plain array.

Raises:

Type Description
InputError

order is used with a non-square result or has the wrong length.

ArgumentError

an element is an array with more than two dimensions.

ValueError

an element cannot be converted to numbers (raised by NumPy).

Metafor reference

bldiag

blsplit

blsplit(
    x: NDArray[float64] | sparray | spmatrix,
    cluster: ArrayLike,
    fun: Callable[..., Any] | None = None,
    args: Any = None,
    sort: bool = False,
) -> dict[Any, Any]

Split a block diagonal matrix into a dict of sub-matrices, one per unique cluster value (metafor's blsplit).

The keys are the unique cluster values in order of appearance (sorted if sort). fun, if given, is applied to each sub-matrix with args as additional positional arguments, i.e. fun(block, *args) (R: blsplit(V, cluster, round, 4); a single value is the one argument). A scipy sparse x gives sparse sub-matrices.

Parameters:

Name Type Description Default
x NDArray[float64] | sparray | spmatrix

A symmetric block diagonal matrix, a dense array or a scipy sparse array.

required
cluster ArrayLike

Clustering variable to split by, with one value per row of x.

required
fun Callable[..., Any] | None

A function applied to each sub-matrix (for example round). None (the default) returns the sub-matrices unchanged.

None
args Any

Additional positional argument(s) for fun, given as fun(block, *args); a single value is the one argument.

None
sort bool

Sort the result by the unique values of cluster instead of their order of appearance (default False).

False

Returns:

Type Description
dict[Any, Any]

A dict (a NamedList) of the sub-matrices (after fun) keyed by the unique values of cluster.

Raises:

Type Description
ArgumentError

x is not a matrix.

InputError

cluster is missing or does not match the dimensions of x, or x is not symmetric.

InternalError

x is neither a dense nor a sparse matrix after the checks above.

Metafor reference

blsplit

pairmat

pairmat(
    x: Any = None,
    btt: int | Sequence[int] | str | None = None,
    btt2: int | Sequence[int] | str | None = None,
    *,
    fixed: bool = False,
) -> DataFrame | PairmatSpec

Rows contrast each pair of the coefficients picked by btt (0-based, or a regex).

For use as anova(res, X=pairmat(res, btt='alloc')), or without the model, anova(res, X=pairmat(btt='alloc')), as in metafor, where the model is that of the anova() or predict() call. Rows for the coefficients picked by btt2 themselves are placed first. fixed=True matches a string btt or btt2 literally instead of as a regular expression (metafor's ... argument). The contrast matrix can be passed to anova (to test the contrasts) and predict (for their confidence intervals).

Parameters:

Name Type Description Default
x Any

A meta-regression model with moderators, fitted by rma_uni, rma_glmm or rma_mv. May be left out (the first argument is then taken as btt) when the result is an argument of an anova or predict call.

None
btt int | Sequence[int] | str | None

The coefficients to construct pairwise contrasts for: 0-based indices, or a string matched as a regular expression against the coefficient names. At least two coefficients are needed.

None
btt2 int | Sequence[int] | str | None

A second set of coefficients (0-based indices or a string) included as rows of their own ('main effects'), placed first. None (the default) for none.

None
fixed bool

Match a string btt or btt2 literally instead of as a regular expression (default False).

False

Returns:

Type Description
DataFrame | PairmatSpec

A data frame with one row per pair of the coefficients picked by btt (labelled name1-name2, with -1 for the first and 1 for

DataFrame | PairmatSpec

the second coefficient) preceded by the rows for btt2 (labelled by the coefficient name, with 1 for it), and one column per model

DataFrame | PairmatSpec

coefficient; as in metafor the rows are named but the columns are not (they are numbered 0, 1, ...). Without a model, a PairmatSpec

DataFrame | PairmatSpec

that anova and predict complete with their model.

Raises:

Type Description
InputError

btt is missing, matches no coefficient or a single coefficient, or the model has no moderators.

Metafor reference

pairmat

Regression on correlation and covariance matrices

matreg

matreg(
    y: int | str,
    x: Sequence[int | str] | int | str | None = None,
    R: ArrayLike | DataFrame | None = None,
    n: float | None = None,
    V: ArrayLike | DataFrame | None = None,
    cov: bool = False,
    means: ArrayLike | None = None,
    ztor: bool = False,
    nearpd: bool = False,
    level: float = 95,
    digits: int | None = None,
) -> MatregResult

Fit a regression model to a correlation or covariance matrix (metafor's matreg).

y is the outcome: a 0-based index into R, a variable name (R must then be a frame with dimension names) or a formula string such as 'perf ~ acog + asom + conf' (which also gives x). x are the predictors (indices or names; by default every other variable). Give either n, the sample size the matrix is based on, or V, the variance-covariance matrix of the elements of the lower triangle of R (column-wise, with the diagonal when cov=True), for instance from :func:metafopy.rcalc or the vcov() of a multivariate model of correlations. cov=True treats R as a covariance matrix (the model then has an intercept, which needs means), ztor=True back-transforms Fisher r-to-z transformed correlations (and their V) and nearpd=True replaces a non-positive-definite R[x, x] by the nearest correlation matrix (:func:metafopy.core.linalg.near_pd, a port of Matrix::nearPD).

Without names, the coefficients are labelled x1, x2, ... by their 1-based position in R, as in R.

Parameters:

Name Type Description Default
y int | str

The outcome variable: a 0-based index into R, a variable name (R must then be a data frame with dimension names) or a formula string such as 'perf ~ acog + asom + conf', which also gives x.

required
x Sequence[int | str] | int | str | None

The predictor variables: a sequence of 0-based indices or names (or a single one). Ignored when y is a formula. None (the default) uses every variable other than y.

None
R ArrayLike | DataFrame | None

The correlation or covariance matrix (an array or data frame; required). Only its lower triangle (including the diagonal) is used.

None
n float | None

The sample size the matrix is based on; gives the standard errors of a regression on raw data (t tests). Give n or V, not both.

None
V ArrayLike | DataFrame | None

The variance-covariance matrix of the elements of the lower triangle of R, column-wise (with the diagonal when cov=True), for instance from rcalc or the vcov() of a multivariate model of correlations. Gives the standard errors by the multivariate delta method (z tests). Give n or V, not both.

None
cov bool

Treat R as a covariance matrix; the model then has an intercept, which needs means (default False, a correlation matrix).

False
means ArrayLike | None

The means of the variables, for the intercept when cov=True. Without them the intercept estimate is NaN.

None
ztor bool

R (and V) hold Fisher r-to-z transformed correlations, which are back-transformed to raw correlations first (default False).

False
nearpd bool

Replace an R[x, x] that cannot be inverted (is not positive definite) by the nearest correlation matrix (a port of Matrix::nearPD) instead of failing (default False). Treat the results with caution. metafor's undocumented nearPD alias of this argument is not accepted.

False
level float

Confidence interval level in percent (default 95), or a value below 1 read as in metafor.

95
digits int | None

Number of decimals used when the result is printed (default 4).

None

Returns:

Type Description
MatregResult

A MatregResult: the table tab of (standardised, for a correlation matrix) regression coefficients with

MatregResult

their standard errors, test statistics, p-values and confidence interval bounds, the variance-covariance matrix vb of the

MatregResult

coefficients, R2 and further fit statistics. It has coef, vcov, confint and predict methods.

Raises:

Type Description
InputError

an argument is missing, invalid or inconsistent with R.

ArgumentError

a logical argument is not a bool.

EstimationError

R[x, x] cannot be inverted, or n does not exceed the number of regression coefficients.

Metafor reference

matreg

MatregResult dataclass

MatregResult(
    tab: DataFrame,
    vb: DataFrame,
    R2: float,
    p: int,
    parms: int,
    digits: int,
    test: Literal['t', 'z'],
    level: float,
    intercept: bool,
    R2adj: float | None = None,
    F: tuple[float, float, float] | None = None,
    Fdf: tuple[float, float] | None = None,
    Fp: float | None = None,
    df_residual: float | None = None,
    sigma2_ml: float | None = None,
    sigma2_reml: float | None = None,
    nobs: float | None = None,
    deviance: float | None = None,
    fit_stats: DataFrame | None = None,
    QM: float | None = None,
    QMdf: tuple[int, None] | None = None,
    QMp: float | None = None,
)

A regression model fitted to a correlation or covariance matrix (metafor's matreg object).

tab holds the columns beta, se, tval and df (test == 't', a model fitted with n) or zval (test == 'z', a model fitted with V), pval, ci.lb and ci.ub. The F test (F, Fdf, Fp), R2adj, the residual variances and fit_stats exist only for test == 't'; the Wald test (QM, QMdf, QMp) only for test == 'z'. level is the alpha level (0.05 for 95%) and intercept is true for a covariance matrix input (cov=True).

Attributes:

Name Type Description
tab DataFrame

Table of coefficients, one row per coefficient (see above for the columns).

vb DataFrame

Variance-covariance matrix of the coefficients.

R2 float

Proportion of variance of the outcome explained by the predictors.

p int

Number of estimated coefficients for a model fitted with n (the intercept included when cov=True); the number of predictors for a model fitted with V.

parms int

Number of estimated parameters: p + 1 for a model fitted with n (the residual variance counts), p for one fitted with V.

digits int

Number of decimals used when the result is printed.

test Literal['t', 'z']

't' for a model fitted with n, 'z' for one fitted with V.

level float

The alpha level of the confidence intervals.

intercept bool

Whether the model has an intercept.

R2adj float | None

Adjusted R^2 (test == 't' only).

F tuple[float, float, float] | None

The F test of the predictors as a tuple (statistic, numerator degrees of freedom, denominator degrees of freedom) (test == 't' only).

Fdf tuple[float, float] | None

Degrees of freedom of the F test (test == 't' only).

Fp float | None

P-value of the F test (test == 't' only).

df_residual float | None

Residual degrees of freedom (test == 't' only).

sigma2_ml float | None

Maximum-likelihood estimate of the residual variance (test == 't' only).

sigma2_reml float | None

Restricted maximum-likelihood estimate of the residual variance (test == 't' only).

nobs float | None

Number of observations (test == 't' only).

deviance float | None

Deviance of the model (test == 't' only).

fit_stats DataFrame | None

Log-likelihood, deviance, AIC, BIC and AICc under ML and REML (test == 't' only).

QM float | None

Wald-type test statistic of the coefficients (test == 'z' only).

QMdf tuple[int, None] | None

Degrees of freedom of the Wald test (test == 'z' only).

QMp float | None

P-value of the Wald test (test == 'z' only).

coef

coef() -> Series

The estimated coefficients (coef.matreg).

vcov

vcov() -> DataFrame

The variance-covariance matrix of the coefficients (vcov.matreg).

sigma

sigma(REML: bool = True) -> float | None

The residual standard deviation (sigma.matreg); None with a warning for a model fitted with V.

logLik

logLik(REML: bool = False) -> LogLik | None

The (restricted) log-likelihood (logLik.matreg), printed as R prints a logLik; None with a warning for a model fitted with V.

AIC

AIC(
    *others: MatregResult,
    k: float = 2,
    correct: bool = False,
    REML: bool = False,
) -> float | DataFrame | None

AIC (or AICc with correct=True) of this fit (AIC.matreg).

With further fits in others a frame with the columns df (number of parameters) and AIC (or AICc), one row per fit. As in metafor, k is accepted but not used.

BIC

BIC(
    *others: MatregResult, REML: bool = False
) -> float | DataFrame | None

BIC of this fit (BIC.matreg); with further fits in others a frame with the columns df and BIC.

table_lines

table_lines(
    digits: int, signif_stars: bool, signif_legend: bool
) -> list[str]

print.matreg.

summary

summary(
    digits: int | None = None,
    signif_stars: bool = True,
    signif_legend: bool | None = None,
) -> str

print(summary(x)): the coefficient table followed by the fit statistics.

MatregConfintResult dataclass

MatregConfintResult(tab: DataFrame, digits: int = 4)

Confidence intervals of a matreg fit: tab has the columns estimate, ci.lb and ci.ub.

Attributes:

Name Type Description
tab DataFrame

Data frame with one row per coefficient and the columns estimate, ci.lb and ci.ub.

digits int

Number of decimals used when the result is printed.

MatregPredictResult dataclass

MatregPredictResult(
    pred: FloatArray,
    se: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    pi_lb: FloatArray,
    pi_ub: FloatArray,
    slab: tuple[str, ...] | None = None,
    pi_se: FloatArray | None = None,
    pi_dist: str | None = None,
    pi_ddf: float | FloatArray | None = None,
    ddf: float | None = None,
    has_pi: bool = True,
    prob: FloatArray | None = None,
    X: DataFrame | None = None,
    vcov: DataFrame | None = None,
    x_names: tuple[str, ...] | None = None,
    digits: int = 4,
    digit_map: Mapping[str, int] | None = None,
    method: str | None = None,
    transf: bool = False,
    pred_type: str = 'location',
)

Bases: PredictResult

Predicted values of a matreg fit (predict.matreg), without prediction intervals (pi_lb and pi_ub are NaN).

X is the matrix of predictor values (addx=True), vcov the variance-covariance matrix of the predicted values (vcov=True without transf), ddf the degrees of freedom of the t-distribution (None for a model fitted with V) and transf whether a transformation was applied (se is then NaN, as in metafor).

The attributes pred, se, ci_lb, ci_ub, pi_lb and pi_ub are those of the predict result.

Attributes:

Name Type Description
X DataFrame | None

Predictor values of the predictions as a data frame, or None (set with addx=True).

vcov DataFrame | None

Variance-covariance matrix of the predicted values, or None (set with vcov=True without transf).

ddf float | None

Degrees of freedom of the t-distribution, or None for a model fitted with V.

digits int

Number of decimals used when the result is printed.

transf bool

Whether a transformation was applied to the predictions.

Estimated marginal means

emmprep

emmprep(
    x: RMAResult
    | RMAMVResult
    | GLMMResult
    | FixedBinaryResult
    | RMALSResult
    | SelmodelResult,
    verbose: bool = False,
    *,
    data: DataFrame | None = None,
    df: float | None = None,
    sigma: float | None = None,
    tran: Link | str | None = None,
    at: Mapping[str, Any] | None = None,
    cov_reduce: Callable[[NDArray[float64]], float]
    | Mapping[str, Callable[[NDArray[float64]], float]]
    | None = None,
    nesting: str
    | Mapping[str, str | Sequence[str]]
    | None
    | Literal['auto'] = 'auto',
) -> EmmGrid

Prepare a reference grid from a fitted model, as metafor's emmprep does for emmeans' qdrg.

The grid has one row per combination of the levels of the factors in the model formula, with each numeric predictor at its mean over the studies (cov_reduce) or at the values given in at. Pass the grid to emmeans (and then to contrast, pairs and regrid) to get estimated marginal means. When the model knows its effect size measure, the back-transformation (for example exponentiation for log ratios) is stored in the grid and applied by type='response'.

Parameters:

Name Type Description Default
x RMAResult | RMAMVResult | GLMMResult | FixedBinaryResult | RMALSResult | SelmodelResult

A fitted model with a formula: a model from rma_uni, rma_mv, rma_glmm, rma_mh or rma_peto, a location-scale model or a selection model. Models with redundant predictors that were dropped cannot be used.

required
verbose bool

Print the extracted formula, degrees of freedom, tau^2 and transformation (default False).

False
data DataFrame | None

Data frame with the variables of the model, to build the grid from instead of the data used in the fit. None (the default) uses the data of the fit.

None
df float | None

Degrees of freedom of the tests and intervals. None (the default) takes them from the fit (the smallest ddf; infinite for z tests).

None
sigma float | None

Error standard deviation used for bias adjustment in back-transformations (the square root of tau^2). None (the default) takes it from the fit, or 0 for rma_mv and location-scale fits, where it cannot be extracted.

None
tran Link | str | None

Transformation of the estimates, a link object or its name (for example 'log' or 'logit'), or 'none' for none. As in emmeans, a name that is no known transformation gives the identity link carrying that name; '+.sqrt' is not supported. None (the default) derives it from the effect size measure ('log' for ratio measures, 'logit' for PLO, and so on).

None
at Mapping[str, Any] | None

Mapping from variable names to the values to use in the grid: for a numeric predictor its values instead of its mean, for a factor a subset of its levels. Other variables are as by default.

None
cov_reduce Callable[[NDArray[float64]], float] | Mapping[str, Callable[[NDArray[float64]], float]] | None

Function reducing the values of a numeric predictor to the one used in the grid, or a mapping from variable names to such functions. None (the default) uses the mean.

None
nesting str | Mapping[str, str | Sequence[str]] | None | Literal['auto']

Factors nested in others, as text such as 'grp %in% lat' (several separated by commas) or a mapping from each nested factor to the factor(s) it is nested in. 'auto' (the default) detects the nesting from the combinations of levels in the data and the terms of the model (lat + lat:grp nests grp in lat); None switches the detection off. Combinations that cannot occur are hidden and left out of the means.

'auto'

Returns:

Type Description
EmmGrid

An EmmGrid: the reference grid, with the coefficients and their variance-covariance matrix, the degrees of freedom

EmmGrid

and the transformation stored.

Raises:

Type Description
ArgumentError

x is not a fitted model of a supported class.

InputError

the fit cannot be used (redundant predictors, no formula or data) or an argument is invalid.

NotSupportedError

tran is '+.sqrt'.

Metafor reference

emmprep

emmeans

emmeans(
    object: EmmGrid
    | (
        RMAResult
        | RMAMVResult
        | GLMMResult
        | FixedBinaryResult
        | RMALSResult
        | SelmodelResult
    ),
    specs: str | Sequence[str],
    by: str | Sequence[str] | None = None,
    *,
    weights: str
    | Sequence[float]
    | Sequence[Sequence[float]]
    | NDArray[float64] = 'equal',
    at: Mapping[str, Any] | None = None,
    cov_reduce: Callable[[NDArray[float64]], float]
    | Mapping[str, Callable[[NDArray[float64]], float]]
    | None = None,
    null: float | None = None,
    delta: float | None = None,
    side: int | float | str | None = None,
    type: str | None = None,
    **prep: Any,
) -> EmmGrid

Estimated marginal means: the reference grid averaged over the variables not named in specs (and by).

object is a reference grid from :func:emmprep or a fit (at, cov_reduce and further keywords then go to :func:emmprep). specs names the variables ('alloc', ['alloc', 'lat'] or an R-style '~ alloc | lat'; '1' or '~ 1' for the overall mean) and by the variables the results are grouped by. weights averages over the other factors with 'equal' weights, 'proportional' (frequencies in the data), 'outer' (products of the marginal frequencies), 'cells' or 'flat' (cell frequencies, the latter ignoring empty cells), a vector with one weight per combination of those factors, or a matrix whose columns are those combinations and whose rows are the weights of the successive means (recycled when there are more means than rows).

With nested factors (see :func:emmprep) the means of a nested factor are given within the groups it is nested in, and the other factors are averaged over the combinations that occur in the data. null, delta and side set the defaults of the tests of :meth:EmmGrid.summary; so does type ('response' shows the back-transformed means by default, as emmeans(..., type='response')). See https://rvlenth.github.io/emmeans/reference/emmeans.html.

Parameters:

Name Type Description Default
object EmmGrid | (RMAResult | RMAMVResult | GLMMResult | FixedBinaryResult | RMALSResult | SelmodelResult)

A reference grid from emmprep, or a fitted model (see emmprep for the classes), for which a grid is made first.

required
specs str | Sequence[str]

The variables to get means for: a name, a sequence of names, or an R-style formula such as '~ alloc | lat'; '1' or '~ 1' for the overall mean.

required
by str | Sequence[str] | None

Variables the results are grouped by. None (the default) for none (or those after | in specs).

None
weights str | Sequence[float] | Sequence[Sequence[float]] | NDArray[float64]

How the other factors are averaged over (a string may be abbreviated, for example 'prop'): 'equal' (the default), 'proportional' (frequencies in the data), 'outer' (products of the marginal frequencies), 'cells' or 'flat' (cell frequencies, the latter ignoring empty cells), a vector with one weight per combination of those factors, or a matrix whose columns are those combinations and whose rows are the weights of the successive means (recycled when there are more means than rows).

'equal'
at Mapping[str, Any] | None

Mapping from variable names to the values of the grid (see emmprep); only when object is a fitted model.

None
cov_reduce Callable[[NDArray[float64]], float] | Mapping[str, Callable[[NDArray[float64]], float]] | None

Reduction of the numeric predictors (see emmprep); only when object is a fitted model.

None
null float | None

Value the tests of the summary compare the estimates with. None keeps the value of the grid (default 0).

None
delta float | None

Threshold of equivalence and non-inferiority tests of the summary. None keeps the value of the grid (default 0).

None
side int | float | str | None

Tail of the tests of the summary: -1, 0 or 1 (or '<', '!=', '>', or a word such as 'left', 'both', 'right', 'noninferiority', 'equivalence'). None keeps the value of the grid (default both sides).

None
type str | None

Default scale of summaries: 'link' (the transformed scale) or 'response' (back-transformed). None (the default) keeps the default of the grid.

None
**prep Any

Further keywords for emmprep (verbose, data, df, sigma, tran, nesting); only when object is a fitted model.

{}

Returns:

Type Description
EmmGrid

An EmmGrid of the estimated marginal means (with summary() to get the table).

Raises:

Type Description
ArgumentError

object is a fitted model of an unsupported class.

InputError

a variable is not in the grid, the weights do not fit the averaged factors, type is not 'link' or 'response', or at, cov_reduce or other emmprep keywords are given with a reference grid.

NotSupportedError

tran is '+.sqrt'.

contrast

contrast(
    object: EmmGrid,
    method: str | Mapping[str, Sequence[float]] = 'eff',
    *,
    by: str | Sequence[str] | None = None,
    interaction: bool | str | Sequence[str] = False,
    name: str = 'contrast',
    adjust: str | None = None,
    ref: int | str | Sequence[int | str] | None = None,
    exclude: int | str | Sequence[int | str] | None = None,
    include: int | str | Sequence[int | str] | None = None,
    reverse: bool = False,
    wts: Sequence[float] | None = None,
    max_degree: int | None = None,
    enhance_levels: bool = True,
    null: float | None = None,
    delta: float | None = None,
    side: int | float | str | None = None,
) -> EmmGrid

Contrasts of the estimates of a reference grid or of marginal means (emmeans' contrast).

method is one of :data:metafopy.methods.emm_contrasts.METHODS ('pairwise', 'revpairwise', 'trt_vs_ctrl', 'trt_vs_ctrlk', 'dunnett', 'eff', 'del_eff', 'consec', 'mean_chg', 'poly', 'identity') or a mapping from contrast names to coefficient vectors, one per row of the grid. The contrasts are formed separately for each combination of the by variables (those of object by default). ref, exclude and include are 0-based indices or level labels. With interaction (True for method on every factor, or one method per factor) contrasts of contrasts are formed, one per combination of the factors. null, delta and side set the defaults of the tests of :meth:EmmGrid.summary.

With nested factors the contrasts are formed within each combination of the groups in by (those a nested factor is nested in are added to it), and the groups can differ in size; only the named methods can be used then. See https://rvlenth.github.io/emmeans/reference/contrast.html.

Parameters:

Name Type Description Default
object EmmGrid

A reference grid or marginal means (EmmGrid).

required
method str | Mapping[str, Sequence[float]]

The contrasts: the name of a method ('pairwise', 'revpairwise', 'tukey', 'trt_vs_ctrl', 'trt_vs_ctrl1', 'trt_vs_ctrlk', 'dunnett', 'eff' (the default), 'del_eff', 'consec', 'mean_chg', 'poly' or 'identity'), or a mapping from contrast names to coefficient vectors with one value per row of the grid (per group).

'eff'
by str | Sequence[str] | None

Variables to form the contrasts within. None (the default) uses those of object.

None
interaction bool | str | Sequence[str]

False (the default) for ordinary contrasts. True forms contrasts of contrasts, applying method to every factor, and a name or sequence of names gives the method for each factor; one contrast per combination of the factors results.

False
name str

Name of the column of the contrasts (default 'contrast').

'contrast'
adjust str | None

Multiplicity adjustment stored in the result for its tests and intervals: 'tukey', 'scheffe', 'sidak', 'dunnettx', 'mvt', 'holm', 'hochberg', 'hommel', 'bonferroni', 'BH', 'BY', 'fdr' or 'none'. None (the default) uses the default of the method (for example 'tukey' for 'pairwise'). As in emmeans, 'tukey', 'scheffe' and 'dunnettx' apply to two-sided tests only, and the methods of p.adjust ('holm' to 'fdr') to tests, not intervals (which then use 'bonferroni').

None
ref int | str | Sequence[int | str] | None

The reference level(s) of 'trt_vs_ctrl' and similar methods: 0-based indices or level labels. Default the first level.

None
exclude int | str | Sequence[int | str] | None

Levels left out of the contrasts: 0-based indices or level labels.

None
include int | str | Sequence[int | str] | None

Levels to use in the contrasts (the others are left out): 0-based indices or level labels.

None
reverse bool

Reverse the direction of the contrasts, for example later minus earlier (default False).

False
wts Sequence[float] | None

Weights of the levels for the 'eff' and 'del_eff' methods, normalised to sum to 1: one value per level, or per included level when exclude or include is used. None (the default) for equal weights. emmeans' wts = NA (take the weights from the grid) is not supported.

None
max_degree int | None

Maximum degree of the 'poly' contrasts (at most 20). None (the default) for min(6, k - 1) with k levels, as the max.degree default of emmeans' poly.emmc.

None
enhance_levels bool

Put the variable name in front of numeric levels in the labels of the contrasts (default True).

True
null float | None

Value the tests of the summary compare the estimates with. None keeps the value of the grid (default 0).

None
delta float | None

Threshold of equivalence and non-inferiority tests of the summary. None keeps the value of the grid (default 0).

None
side int | float | str | None

Tail of the tests of the summary: -1, 0 or 1 (or '<', '!=', '>', or a word such as 'left', 'both', 'right', 'noninferiority', 'equivalence'). None keeps the value of the grid (default both sides).

None

Returns:

Type Description
EmmGrid

An EmmGrid of the contrasts, with one row per contrast.

Raises:

Type Description
InputError

the method or an argument does not fit the grid.

pairs

pairs(
    object: EmmGrid,
    reverse: bool = False,
    *,
    by: str | Sequence[str] | None = None,
    adjust: str | None = None,
    null: float | None = None,
    delta: float | None = None,
    side: int | float | str | None = None,
) -> EmmGrid

All pairwise differences of the estimates (emmeans' pairs): contrast(object, 'pairwise').

Parameters:

Name Type Description Default
object EmmGrid

A reference grid or marginal means (EmmGrid).

required
reverse bool

Give later minus earlier instead of earlier minus later, that is contrast(object, 'revpairwise') (default False).

False
by str | Sequence[str] | None

Variables to form the differences within. None (the default) uses those of object.

None
adjust str | None

Multiplicity adjustment of the tests and intervals (see contrast). None (the default) uses 'tukey'.

None
null float | None

Value the tests of the summary compare the estimates with. None keeps the value of the grid (default 0).

None
delta float | None

Threshold of equivalence and non-inferiority tests of the summary. None keeps the value of the grid (default 0).

None
side int | float | str | None

Tail of the tests of the summary: -1, 0 or 1 (or '<', '!=', '>', or a word such as 'left', 'both', 'right', 'noninferiority', 'equivalence'). None keeps the value of the grid (default both sides).

None

Returns:

Type Description
EmmGrid

An EmmGrid of the pairwise differences.

Raises:

Type Description
InputError

an argument does not fit the grid.

regrid

regrid(
    object: EmmGrid,
    *,
    bias_adjust: bool = False,
    sigma: float | None = None,
) -> EmmGrid

Back-transform the estimates, so that later contrasts are of the back-transformed values (emmeans' regrid).

The variance-covariance matrix of the transformed estimates follows by the delta method. Without a transformation the grid is returned as is, with an identity linfct. Only the default transform = 'response' of emmeans is available: there are no transform, inv_link_lbl, predict_type, N_sim or sim arguments. See https://rvlenth.github.io/emmeans/reference/regrid.html.

Parameters:

Name Type Description Default
object EmmGrid

A reference grid or marginal means (EmmGrid).

required
bias_adjust bool

Adjust the back-transformation for the bias that comes from the variation of the true effects, using sigma (default False).

False
sigma float | None

Error standard deviation for the bias adjustment. None (the default) uses the one stored in the grid.

None

Returns:

Type Description
EmmGrid

An EmmGrid whose estimates are the back-transformed values.

Raises:

Type Description
InputError

bias_adjust without a valid sigma.

EmmGrid dataclass

EmmGrid(
    grid: DataFrame,
    levels: dict[str, tuple[Any, ...]],
    numeric: tuple[str, ...],
    linfct: FloatArray,
    bhat: FloatArray,
    vb: FloatArray,
    df: float,
    wgt: FloatArray | None,
    est_name: str,
    est_type: str,
    by: tuple[str, ...],
    adjust: str,
    fam_size: int,
    infer: tuple[bool, bool],
    link: Link | None,
    inv_label: str | None,
    log_contrast: bool,
    sigma: float | None,
    avgd_over: tuple[str, ...],
    messages: tuple[str, ...],
    pairby: tuple[str, ...] | None,
    pri_vars: tuple[str, ...],
    level: float = 0.95,
    measure: str = 'GEN',
    nesting: dict[str, tuple[str, ...]] = dict(),
    display: tuple[bool, ...] | None = None,
    avgd_qualifier: str = '',
    null: float = 0.0,
    delta: float = 0.0,
    side: int = 0,
    summary_type: str | None = None,
)

A reference grid, a set of estimated marginal means, or contrasts of them (emmeans' emmGrid).

grid has one row per estimate and one column per variable; the estimates are linfct @ bhat with the variance-covariance matrix linfct @ vb @ linfct.T and degrees of freedom df (infinite for z tests). wgt holds the number of studies behind each row of a reference grid, which the weights of :func:emmeans use. link is the transformation of the estimates (type='response' of :meth:summary back-transforms them), inv_label the name of the back-transformed estimate and sigma the error SD used for the bias adjustment. nesting maps each nested factor to the factors it is nested in, and display marks the rows of the grid that occur (the others are hidden from summaries and left out of the averages). null, delta and side are the defaults of the tests of :meth:summary, summary_type the default type.

Attributes:

Name Type Description
grid DataFrame

Data frame with one row per estimate and one column per variable.

levels dict[str, tuple[Any, ...]]

The levels of each factor, by variable name.

numeric tuple[str, ...]

Names of the numeric predictors.

linfct FloatArray

Matrix of linear functions: each row gives an estimate as a combination of the model coefficients bhat.

bhat FloatArray

The model coefficients.

vb FloatArray

Variance-covariance matrix of the model coefficients.

df float

Degrees of freedom of the tests and intervals (infinite for z tests).

wgt FloatArray | None

Number of studies behind each row of a reference grid, used by proportional weights, or None.

est_name str

Name of the estimate column in summaries (for example 'prediction', 'emmean' or 'estimate').

est_type str

What the estimates are (for example 'prediction').

by tuple[str, ...]

Variables the results are grouped by.

adjust str

Multiplicity adjustment of the tests and intervals.

fam_size int

Number of estimates in a family, used by the adjustments.

infer tuple[bool, bool]

Whether summaries give confidence intervals and tests, as a pair.

link Link | None

Transformation of the estimates, or None.

inv_label str | None

Name of the back-transformed estimate, or None.

log_contrast bool

Whether the contrasts are of log-scale estimates (so back-transformed they are ratios).

sigma float | None

Error SD used for the bias adjustment, or None.

avgd_over tuple[str, ...]

Variables the estimates are averaged over.

messages tuple[str, ...]

Notes printed under summaries.

pairby tuple[str, ...] | None

Variables of a pairwise grouping, or None.

pri_vars tuple[str, ...]

Names of the primary variables.

level float

Confidence level of the intervals (default 0.95).

measure str

The effect size measure of the model.

nesting dict[str, tuple[str, ...]]

Maps each nested factor to the factors it is nested in.

display tuple[bool, ...] | None

Flags for the rows of the grid that occur, or None for all.

avgd_qualifier str

Qualifier printed in the note about the averaging.

null float

Default null value of the tests.

delta float

Default threshold of equivalence tests.

side int

Default tail of the tests (-1, 0 or 1).

summary_type str | None

Default type of summaries ('link' or 'response'), or None.

estimate property

estimate: FloatArray

The estimates on the link scale.

vcov property

vcov: FloatArray

The variance-covariance matrix of the estimates.

summary

summary(**kwargs: Any) -> EmmSummary

The estimates with standard errors, intervals and tests; see :func:metafopy.methods.emm_summary.summary.

confint

confint(**kwargs: Any) -> EmmSummary

The summary with confidence intervals only.

test

test(**kwargs: Any) -> EmmSummary

The summary with tests only.

EmmSummary dataclass

EmmSummary(
    frame: DataFrame,
    est_name: str,
    cl_names: tuple[str, ...],
    by: tuple[str, ...],
    adjust: str,
    type: str,
    messages: tuple[str, ...],
)

The table of a summary with the notes emmeans prints under it (messages).

frame has a column for each variable, the estimate (emmean, estimate, response, ratio, ...), SE, df, the confidence limits (lower.CL/upper.CL, or asymp.LCL/asymp.UCL for z tests), null, the t.ratio (z.ratio) and the p.value, as far as they were asked for.

Attributes:

Name Type Description
frame DataFrame

The table, a data frame.

est_name str

Name of the estimate column.

cl_names tuple[str, ...]

Names of the lower and upper confidence limit columns.

by tuple[str, ...]

Variables the results are grouped by.

adjust str

Multiplicity adjustment used.

type str

The scale shown, 'link' or 'response'.

messages tuple[str, ...]

Notes printed under the table.

Random number generator

set_seed

set_seed(seed: int) -> RRandom

Seed the module-level random number generator (R's set.seed()).

The generator reproduces R's default Mersenne-Twister with rejection sampling. The functions that draw random numbers when they are given no seed or rng use this generator: among them permutest, gosh (with random subsets), hettest (the bootstrap), vif (with sim=True), fsn (with exact=True), qqnorm (the envelope) and conv_fivenum (methods 'bc' and 'mln'). After set_seed(s) the results of permutest, gosh, hettest, vif and conv_fivenum were compared with those of metafor after set.seed(s) and agree. Without a call the generator is seeded from the clock on first use.

Parameters:

Name Type Description Default
seed int

The integer seed, as given to R's set.seed().

required

Returns:

Type Description
RRandom

The new generator, an RRandom that can also be passed to functions that take an rng argument.