Package {medfit}


Type: Package
Title: Infrastructure for Mediation Model Fitting and Extraction
Version: 0.21.3
Date: 2026-11-26
Description: Provides S7-based infrastructure for fitting mediation models, extracting path coefficients, and performing bootstrap inference. Designed as a foundation package for the mediation analysis ecosystem, supporting 'probmed', 'RMediation', and 'medrobust' packages. Implements unified interfaces for model fitting across different engines (generalized linear models, linear mixed models for cluster-randomized designs, and a maximum-likelihood structural equation engine; Bayesian methods are planned), standardized extraction of mediation paths from various model types, and robust bootstrap inference methods. Mediation methods are described in MacKinnon, Lockwood and Williams (2004) <doi:10.1207/s15327906mbr3901_4>, Preacher and Hayes (2008) <doi:10.3758/brm.40.3.879>, Tofighi and MacKinnon (2011) <doi:10.3758/s13428-011-0076-x>, and VanderWeele (2014) <doi:10.1097/EDE.0000000000000121>.
License: GPL (≥ 3)
URL: https://data-wise.github.io/medfit/, https://github.com/data-wise/medfit
BugReports: https://github.com/data-wise/medfit/issues
Depends: R (≥ 4.1.0)
Imports: S7 (≥ 0.1.0), stats, methods, checkmate, generics, lifecycle, MASS, nloptr (≥ 1.0.4), rlang
Suggests: knitr, lavaan (≥ 0.7-3), lme4, numDeriv, OpenMx, pbkrtest, regmedint, RMediation, sandwich, testthat (≥ 3.0.0), tibble, withr, yaml
Encoding: UTF-8
Language: en-US
Config/testthat/edition: 3
Config/Needs/website: knitr, rmarkdown, quarto
Config/roxygen2/version: 8.1.1
LazyData: true
NeedsCompilation: no
Packaged: 2026-11-27 22:56:27 UTC; davood
Author: Davood Tofighi ORCID iD [aut, cre, cph]
Maintainer: Davood Tofighi <dtofighi@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-28 11:50:02 UTC

medfit: Infrastructure for Mediation Model Fitting and Extraction

Description

Provides S7-based infrastructure for fitting mediation models, extracting path coefficients, and performing bootstrap inference. Designed as a foundation package for probmed, RMediation, and medrobust.

Details

Key functions:

Key classes:

Author(s)

Maintainer: Davood Tofighi dtofighi@gmail.com (ORCID) [copyright holder]

Authors:

See Also

Useful links:


BootstrapResult S7 Class

Description

S7 class containing results from bootstrap inference, including point estimates, confidence intervals, and bootstrap distribution.

Usage

BootstrapResult(estimate, ci_lower, ci_upper, ci_level, boot_estimates,
  n_boot, method, call, inference = list())

Arguments

estimate

Numeric scalar: point estimate of the statistic

ci_lower

Numeric scalar: lower bound of confidence interval

ci_upper

Numeric scalar: upper bound of confidence interval

ci_level

Numeric scalar: confidence level (e.g., 0.95 for 95% CI)

boot_estimates

Numeric vector: bootstrap distribution of estimates

n_boot

Integer scalar: number of bootstrap samples

method

Character scalar: bootstrap method ("parametric", "nonparametric", or "plugin")

call

Call object or NULL: original function call

inference

Optional list, empty by default for legacy results. Bounded FIML source intervals use schema fiml-bootstrap-1 for method/target, source and RNG provenance, retained/collected counts and every requested replicate outcome.

Details

This class standardizes bootstrap inference results across different bootstrap methods (parametric, nonparametric, plugin).

The class includes validation to ensure consistency between method type and required fields. See bootstrap_mediation() for the bounded FIML source route. Its failed or incomplete results retain length-n_boot distributions with unresolved NA values and withhold intervals through every accessor. The optional metadata does not change legacy tidy/glance columns.

Value

A BootstrapResult S7 object

Examples


# Parametric bootstrap result
result <- BootstrapResult(
  estimate = 0.15,
  ci_lower = 0.10,
  ci_upper = 0.20,
  ci_level = 0.95,
  boot_estimates = rnorm(1000, 0.15, 0.02),
  n_boot = 1000L,
  method = "parametric",
  call = NULL
)



ClusterMediationData: Cluster-Level Treatment Mediation (2-1-1)

Description

S7 class for mediation with a treatment assigned to whole clusters (such as schools) and a mediator and outcome measured on the individuals in them. It holds the paths of a two-level linear mixed model pair: the mediator model M ~ X + ... + (1 | cluster) and the outcome model with the mediator split into its within-cluster deviation and the observed cluster mean. medfit computes the effects; causal interpretation is the user's responsibility.

Usage

ClusterMediationData(a_path, b_within, b_between, c_prime, estimates, vcov,
  kr_df, treatment, mediator, outcome, cluster, n_obs, n_clusters,
  cluster_sizes, parameterization, covariates_centered, se_type, reml,
  converged, sigma_m, sigma_y, tau_m, tau_y, data, source_package)

Arguments

a_path

Numeric scalar: effect of the treatment on the mediator.

b_within

Numeric scalar: within-cluster mediator effect on the outcome.

b_between

Numeric scalar: between-cluster (cluster-mean) mediator effect on the outcome.

c_prime

Numeric scalar: direct effect of the treatment.

estimates

Named numeric vector of parameter estimates: the four alias rows plus each model's fixed effects.

vcov

Square variance-covariance matrix of estimates, with matching dimnames.

kr_df

Named numeric vector of Kenward-Roger degrees of freedom, one per path, when se_type = "kr"; NULL otherwise.

treatment, mediator, outcome

Character names of the variables.

cluster

Character name of the cluster variable.

n_obs

Integer number of observations.

n_clusters

Integer number of clusters.

cluster_sizes

Integer vector with one size per cluster.

parameterization

"within" or "raw": how the outcome model was fitted.

covariates_centered

Logical: whether every level-1 covariate in the outcome model has a cluster-mean companion.

se_type

"model" or "kr".

reml

Logical: whether the models were fitted by REML.

converged

Logical convergence flag.

sigma_m, sigma_y

Numeric scalars: residual standard deviations of the mediator and outcome models.

tau_m, tau_y

Numeric scalars: random-intercept standard deviations of the mediator and outcome models.

data

Optional data frame, or NULL.

source_package

Character name of the originating package.

Details

With the within parameterization Y_{ij} = \theta_0 + c' X_j + b_W (M_{ij} - \bar M_j) + b_B \bar M_j + \dots and a the effect of the treatment on the mediator, the natural indirect effect is a b_B. It splits into an own-mediator part a b_W and a spillover part a (b_B - b_W).

The split is the large-cluster, cluster-average approximation. With the observed cluster mean, moving only member i's mediator by a also moves the mean by a / n_j, so the exact own-mediator effect is a [b_W + (b_B - b_W) / n_j] and the exact spillover is a (b_B - b_W)(n_j - 1) / n_j; they still sum to a b_B. decompose() warns when the approximation error exceeds half the own effect's standard error.

The estimand assumes randomized treatment, intact clusters, no interference between clusters, linear models without mediator-by-treatment or mediator-by-covariate products, and interference through the observed cluster mean only; all members of a cluster must be in the analysis rows. The own effect also needs no unmeasured lower-level mediator-outcome confounding. The spillover, NIE and NDE need no unmeasured upper-level mediator-outcome confounding either; under it only the sum of the direct effect and a (b_B - b_W) is identified. print() and summary() print this block. The validator ties the alias rows a, c_prime, b_within and b_between of estimates and vcov to the path properties, so an object with inconsistent numbers cannot be built.

kr_df holds the Kenward-Roger degrees of freedom of each path when se_type = "kr", and is empty otherwise.

Value

A ClusterMediationData S7 object.

References

Talloen, W., Moerkerke, B., Loeys, T., De Naeghel, J., Van Keer, H., & Vansteelandt, S. (2016). Estimation of indirect effects in the presence of unmeasured confounding for the mediator-outcome relationship in a multilevel 2-1-1 mediation model. Journal of Educational and Behavioral Statistics, 41(4), 359-391. doi:10.3102/1076998616636855

VanderWeele, T. J. (2010). Direct and indirect effects for neighborhood-based clustered and longitudinal data. Sociological Methods & Research, 38(4), 515-544. doi:10.1177/0049124110366236

Examples

# Hand-built object (the paths and their alias rows must agree)
est <- c(a = 0.5, c_prime = 0.2, b_within = 0.3, b_between = 0.6)
vc <- diag(0.01, 4)
dimnames(vc) <- list(names(est), names(est))
cmd <- ClusterMediationData(
  a_path = 0.5, b_within = 0.3, b_between = 0.6, c_prime = 0.2,
  estimates = est, vcov = vc,
  treatment = "X", mediator = "M", outcome = "Y", cluster = "school",
  n_obs = 400L, n_clusters = 40L, cluster_sizes = rep(10L, 40),
  parameterization = "within", covariates_centered = TRUE, se_type = "model",
  reml = TRUE, converged = TRUE, sigma_m = 1, sigma_y = 1, tau_m = 0.5,
  tau_y = 0.5, source_package = "medfit"
)
cmd@a_path * cmd@b_between  # the NIE, 0.5 * 0.6


InteractionMediationData: Mediation with Treatment-Mediator Interaction

Description

S7 class for simple mediation with a treatment-by-mediator interaction (X \rightarrow M \rightarrow Y where the outcome model contains an X \times M term). It carries VanderWeele's (2014) four-way decomposition of the total effect into controlled direct effect (CDE), reference interaction (INTref), mediated interaction (INTmed), and pure indirect effect (PIE):

TE = CDE + INTref + INTmed + PIE

with NDE = CDE + INTref and NIE = INTmed + PIE. medfit computes the decomposition; causal interpretation is the user's responsibility (it requires the four no-unmeasured-confounding assumptions of VanderWeele 2014).

Usage

InteractionMediationData(a_path, b_path, c_prime, interaction, cde,
  int_ref, int_med, pie, nde, nie, total_effect, m_star, estimates, vcov,
  sigma_m, sigma_y, treatment, mediator, outcome, mediator_predictors,
  outcome_predictors, data, n_obs, converged, source_package)

Arguments

a_path

Numeric scalar: treatment -> mediator effect (\beta_1).

b_path

Numeric scalar: mediator -> outcome main effect (\theta_2).

c_prime

Numeric scalar: treatment -> outcome main effect (\theta_1).

interaction

Numeric scalar: treatment x mediator coefficient (\theta_3).

cde, int_ref, int_med, pie

Numeric scalars: the four-way components (controlled direct, reference interaction, mediated interaction, pure indirect).

nde, nie, total_effect

Numeric scalars: derived natural direct effect (CDE + INTref), natural indirect effect (INTmed + PIE), and total effect (the sum of all four components).

m_star

Numeric scalar: reference mediator level for the decomposition (default 0).

estimates

Numeric vector of all parameter estimates.

vcov

Square variance-covariance matrix of estimates.

sigma_m

Optional numeric scalar mediator residual SD, or NULL.

sigma_y

Optional numeric scalar outcome residual SD, or NULL.

treatment, mediator, outcome

Single character strings naming the treatment / mediator / outcome.

mediator_predictors, outcome_predictors

Character vectors of predictor names for the mediator and outcome models.

data

Optional data frame, or NULL.

n_obs

Integer number of observations.

converged

Logical convergence flag.

source_package

Character name of the originating package.

Details

Path coefficients follow the outcome model Y = \theta_0 + \theta_1 X + \theta_2 M + \theta_3 XM + \dots and mediator model M = \beta_0 + \beta_1 X + \dots: a_path = \beta_1, b_path = \theta_2, c_prime = \theta_1, interaction = \theta_3. With reference level m_star (m^*) the components are CDE = \theta_1 + \theta_3 m^*, INTref = \theta_3 (E[M \mid X = 0, \bar c] - m^*), INTmed = \theta_3 \beta_1, and PIE = \theta_2 \beta_1. When \theta_3 = 0 the decomposition collapses to standard simple mediation (CDE = NDE = \theta_1; INTref = INTmed = 0; NIE = PIE = \theta_2\beta_1).

E[M \mid X = 0, \bar c] = \beta_0 + \gamma^\top \bar c is the mediator model's prediction at no treatment and the covariate means \bar c. The effects are for the treatment contrast 0 to 1, and the lm/glm extractor requires Gaussian identity-link models. From fit_mediation(engine = "regmedint"), ⁠@estimates⁠ and ⁠@vcov⁠ also carry regmedint's own delta-method covariance of the four components and the derived effects.

Value

An InteractionMediationData S7 object.

References

VanderWeele, T. J. (2014). A unification of mediation and interaction: A 4-way decomposition. Epidemiology, 25(5), 749–761.

Examples

# Hand-built object (theta3 = 0.2 interaction, m* = 0)
imd <- InteractionMediationData(
  a_path = 0.5, b_path = 0.3, c_prime = 0.1, interaction = 0.2,
  cde = 0.1, int_ref = 0.04, int_med = 0.10, pie = 0.15,
  nde = 0.14, nie = 0.25, total_effect = 0.39, m_star = 0,
  estimates = c(a = 0.5, b = 0.3, c_prime = 0.1, theta3 = 0.2),
  vcov = diag(0.01, 4),
  treatment = "X", mediator = "M", outcome = "Y",
  mediator_predictors = "X", outcome_predictors = c("X", "M", "X:M"),
  n_obs = 200L, converged = TRUE, source_package = "medfit"
)

nie(imd)       # INTmed + PIE = 0.25
decompose(imd) # all four components + derived effects


JointMediationData: Joint Natural Effects of Multiple Mediators

Description

S7 class for the joint natural effects of two or more mediators, serial or parallel, when the outcome model may contain treatment-by-mediator product terms (VanderWeele and Vansteelandt 2014). The mediators are treated as one block: the natural indirect effect (NIE) runs through every mediator and every path among them, and the natural direct effect (NDE) is the remainder. medfit computes the effects; causal interpretation is the user's responsibility.

Usage

JointMediationData(structure, mediators, treatment, outcome, interactions,
  a_total, b_paths, theta3, c_prime, cde, nde, nie, total_effect, m_star,
  estimates, vcov, data, n_obs, converged, source_package)

Arguments

structure

Single string, "serial" or "parallel".

mediators

Character vector of mediator names, in causal order.

treatment, outcome

Single character strings.

interactions

Character vector naming the mediators that carry a treatment-by-mediator product in the outcome model (may be empty).

a_total

Numeric vector named by mediators: total effect of the treatment on each mediator (\beta^*_{1i}).

b_paths

Numeric vector named by mediators: outcome main effect of each mediator (\theta_{2i}).

theta3

Numeric vector named by interactions: product coefficients (\theta_{3i}).

c_prime

Numeric scalar: treatment main effect on the outcome (\theta_1).

cde, nde, nie, total_effect

Numeric scalars: controlled direct, natural direct, natural indirect and total effects.

m_star

Numeric vector named by interactions: reference mediator levels for the CDE.

estimates

Named numeric vector of parameter estimates.

vcov

Square variance-covariance matrix of estimates.

data

Optional data frame, or NULL.

n_obs

Integer number of observations.

converged

Logical convergence flag.

source_package

Character name of the originating package.

Details

With outcome model Y = \theta_1 X + \sum_i (\theta_{2i} + \theta_{3i} X) M_i + \dots and \beta^*_{1i} the total (propagated) effect of the treatment on mediator i (for a serial chain this includes the paths through earlier mediators), the unit-contrast effects are

NIE = \sum_i (\theta_{2i} + \theta_{3i}) \beta^*_{1i}

NDE = \theta_1 + \sum_i \theta_{3i} \mu^*_{0i}

CDE = \theta_1 + \sum_i \theta_{3i} m^*_i

and TE = NDE + NIE. \theta_{3i} is zero for a mediator without a product term, and \mu^*_{0i} is the mean of mediator i under no treatment at the covariate means (propagated down a serial chain like \beta^*_{1i}). The validator enforces the NIE and CDE identities, so an object with inconsistent numbers cannot be built.

What the joint NIE is, and is not

The NIE is the effect through the mediators as a block: every path from the treatment through any mediator, including paths among the mediators. It is not split into per-mediator or per-path pieces, and none of its parts should be reported as the effect "through M1". For a serial chain it therefore differs from the default nie() of a SerialMediationData (a * d * b, the effect through the full chain only): with no product term, the joint NIE of M1 -> M2 is a_1 b_1 + (a_2 + d a_1) b_2, not a_1 d b_2. The effects use the unit contrast of a 0/1 treatment (0 to 1).

Assumptions

The joint effects are identified under no-unmeasured-confounding assumptions stated for the whole mediator vector: none for the treatment and outcome, none for the mediators and the outcome, none for the treatment and the mediators, and no mediator-outcome confounder affected by the treatment outside the mediator vector (VanderWeele and Vansteelandt 2014). In a serial chain the earlier mediators are affected by the treatment and confound the later ones; that is allowed precisely because they are part of the vector. Mediator-outcome and treatment-mediator confounders must be controlled for every mediator.

medfit's requirements

Covariates and standard errors

The NDE depends on the covariates; it is evaluated at their sample means. The effects are linear in the covariates, so this equals the sample average of the per-observation effects. Standard errors use the delta method with analytic gradients over a stacked-OLS covariance that includes the correlation between parallel mediator equations. They treat the covariate means as fixed, so they are conditional on the observed covariates and slightly understate the uncertainty of a population-average effect. For a parametric bootstrap use joint_effects() as the statistic.

Value

A JointMediationData S7 object.

References

VanderWeele, T. J., & Vansteelandt, S. (2014). Mediation analysis with multiple mediators. Epidemiologic Methods, 2(1), 95–115. doi:10.1515/em-2012-0010

Examples

# Hand-built parallel object with an X x M2 product (m2* = 0)
jmd <- JointMediationData(
  structure = "parallel", mediators = c("M1", "M2"),
  treatment = "X", outcome = "Y", interactions = "M2",
  a_total = c(M1 = 0.5, M2 = 0.3), b_paths = c(M1 = 0.3, M2 = 0.4),
  theta3 = c(M2 = 0.2), c_prime = 0.1,
  cde = 0.1, nde = 0.12, nie = 0.33, total_effect = 0.45,
  m_star = c(M2 = 0),
  estimates = c(a1 = 0.5, a2 = 0.3, b1 = 0.3, b2 = 0.4,
                theta3_M2 = 0.2, c_prime = 0.1),
  vcov = diag(0.01, 6),
  n_obs = 200L, converged = TRUE, source_package = "medfit"
)
jmd@nie  # (0.3 + 0) * 0.5 + (0.4 + 0.2) * 0.3 = 0.33


MediationData S7 Class

Description

S7 class containing standardized mediation model structure, including path coefficients, parameter estimates, variance-covariance matrix, and metadata.

Usage

MediationData(a_path, b_path, c_prime, estimates, vcov, sigma_m, sigma_y,
  family_m, family_y, treatment, mediator, outcome, mediator_predictors,
  outcome_predictors, data, n_obs, converged, source_package)

Arguments

a_path

Numeric scalar: effect of treatment on mediator (a path)

b_path

Numeric scalar: effect of mediator on outcome (b path)

c_prime

Numeric scalar: direct effect of treatment on outcome (c' path)

estimates

Numeric vector: all parameter estimates

vcov

Numeric matrix: variance-covariance matrix of estimates

sigma_m

Numeric scalar or NULL: residual SD for mediator model

sigma_y

Numeric scalar or NULL: residual SD for outcome model

family_m

GLM family object (or NULL): family/link for the mediator model (e.g. gaussian(), binomial()). Defaults to unset (empty), which consumers treat as Gaussian.

family_y

GLM family object (or NULL): family/link for the outcome model. Required by scale-free estimands (e.g. probmed) to simulate non-Gaussian potential outcomes on the correct scale. Defaults to unset (empty), treated as Gaussian.

treatment

Character scalar: name of treatment variable

mediator

Character scalar: name of mediator variable

outcome

Character scalar: name of outcome variable

mediator_predictors

Character vector: predictor names in mediator model

outcome_predictors

Character vector: predictor names in outcome model

data

Data frame or NULL: original data

n_obs

Integer scalar: number of observations

converged

Logical scalar: whether models converged

source_package

Character scalar: package/engine used for fitting

Details

This class provides a unified container for mediation model information extracted from various model types (lm, glm, lavaan, etc.). It ensures consistency across the mediation analysis ecosystem.

The class includes comprehensive validation to ensure data integrity.

Value

A MediationData S7 object

Examples


# Create a MediationData object
med_data <- MediationData(
  a_path = 0.5,
  b_path = 0.3,
  c_prime = 0.2,
  estimates = c(0.5, 0.3, 0.2),
  vcov = diag(3) * 0.01,
  sigma_m = 1.0,
  sigma_y = 1.2,
  treatment = "X",
  mediator = "M",
  outcome = "Y",
  mediator_predictors = "X",
  outcome_predictors = c("X", "M"),
  data = NULL,
  n_obs = 100L,
  converged = TRUE,
  source_package = "stats"
)



ParallelMediationData: Parallel (Multiple-Mediator) Mediation Structure

Description

S7 class for parallel mediation, where a treatment affects an outcome through two or more independent mediators operating in parallel (X \rightarrow M_j \rightarrow Y for j = 1, \dots, k). The total indirect effect is the sum of the per-mediator products, \sum_{j=1}^{k} a_j b_j. This complements MediationData (simple) and SerialMediationData (serial chains).

Usage

ParallelMediationData(a_paths, b_paths, c_prime, estimates, vcov,
  sigma_mediators, sigma_y, treatment, mediators, outcome,
  mediator_predictors, outcome_predictors, data, n_obs, converged,
  source_package)

Arguments

a_paths

Numeric vector: treatment -> mediator effects (a_1, \dots, a_k).

b_paths

Numeric vector: mediator -> outcome effects (b_1, \dots, b_k); must be the same length as a_paths.

c_prime

Numeric scalar: direct effect X \rightarrow Y.

estimates

Numeric vector of all parameter estimates.

vcov

Square variance-covariance matrix of estimates.

sigma_mediators

Optional numeric vector of mediator residual SDs (length k), or NULL.

sigma_y

Optional numeric scalar outcome residual SD, or NULL.

treatment, outcome

Single character strings naming the treatment / outcome.

mediators

Character vector of mediator names (length k, unique).

mediator_predictors

List of predictor-name vectors, one per mediator.

outcome_predictors

Character vector of outcome-model predictor names.

data

Optional data frame, or NULL.

n_obs

Integer number of observations.

converged

Logical convergence flag.

source_package

Character name of the originating package.

Value

A ParallelMediationData S7 object.

Examples

pmd <- ParallelMediationData(
  a_paths = c(0.5, 0.4),
  b_paths = c(0.6, 0.3),
  c_prime = 0.2,
  estimates = c(0.5, 0.4, 0.6, 0.3, 0.2),
  vcov = diag(0.01, 5),
  treatment = "X",
  mediators = c("M1", "M2"),
  outcome = "Y",
  mediator_predictors = list("X", "X"),
  outcome_predictors = c("X", "M1", "M2"),
  n_obs = 200L,
  converged = TRUE,
  source_package = "medfit"
)

nie(pmd)   # total indirect effect: sum(a_j * b_j) = 0.42
paths(pmd) # a1, b1, a2, b2, c_prime


SEMFit S7 Class

Description

S7 class holding a structural equation model fitted by the sem engine, medfit's own maximum-likelihood SEM fitter (see fit_sem()): estimates, their covariance, the parameter table, defined parameters (⁠:=⁠) with delta-method standard errors, and the diagnostics of the optimizer.

Usage

SEMFit(theta, vcov, table, defined, f, n_obs, n_dropped, df, information,
  converged, data, model, diagnostics, internals, call)

Arguments

theta

Named numeric vector: free-parameter estimates

vcov

Numeric matrix: covariance of theta (projected onto the active constraints and bounds; NA when the model is not identified)

table

Data frame: one row per parameter-table row with lhs, op, rhs, label, free, est and se

defined

Data frame of ⁠:=⁠ parameters: name, expr, est, se

f

Numeric scalar: minimized maximum-likelihood discrepancy; NA for bounded FIML

n_obs, n_dropped

Integer scalars: rows used and rows dropped for missing values (listwise deletion by default; only all-empty model rows for FIML)

df

Numeric scalar: model-test degrees of freedom; NA for bounded FIML, which stores the free-parameter count separately in internals$likelihood$k

information

Character scalar: "observed" or "expected"

converged

Logical scalar: the acceptance gate passed. fit_sem() returns a fit only for an accepted solution (otherwise it errors), so this is TRUE for every fit it returns and glance() does not report it

data

Data frame: the rows used, on the model's observed variables

model

Character scalar: the model syntax

diagnostics

List: the versioned outcome ledger (see fit_sem()) and optimizer diagnostics (status, decrement, retries, active_bounds, active_constraints, improper, sign_check, and optimum: a list with n_starts, n_accepted, best_of, certified, spread (discrepancy range among accepted starts, NA when fewer than two or not best-of), and status (unique, certified, agreed, disagreed, or single))

internals

List: the internal index objects the engine needs (ram, par_map, constraints); not part of the interface

call

Call object or NULL: the call that produced the fit

Value

A SEMFit S7 object

See Also

fit_sem()

Examples


fit <- fit_sem(
  "mediator1 ~ a*treatment\noutcome ~ b*mediator1 + treatment\nab := a*b",
  data = mediation_demo, fixed_x = FALSE, meanstructure = NULL
)
fit@table[fit@table$op == "~", c("lhs", "rhs", "est", "se")]
fit@defined
fit@converged



Methods for SEMFit objects

Description

Accessors and display for a SEMFit returned by fit_sem().

Details

These are S7 methods for the base generics, so there is no separate usage section; each takes the SEMFit object as its first argument (object, or x for print()) and ignores further arguments in ....

Value

coef() a named numeric vector; vcov() a matrix; nobs() an integer; logLik() an object of class "logLik"; summary() an object of class "summary_SEMFit"; print() invisibly returns its argument.

See Also

fit_sem(), SEMFit

Examples


fit <- fit_sem(
  "mediator1 ~ a*treatment\noutcome ~ b*mediator1 + treatment\nab := a*b",
  data = mediation_demo, fixed_x = FALSE, meanstructure = NULL
)
coef(fit)
vcov(fit)[c("a", "b"), c("a", "b")]
nobs(fit)
summary(fit)
generics::tidy(fit, conf_int = TRUE)
generics::glance(fit)

# a likelihood-ratio test of b = 0 against the fitted model
fit0 <- fit_sem(paste0(fit@model, "\nb == 0"), data = mediation_demo,
  fixed_x = FALSE, meanstructure = NULL)
anova(fit, fit0)



SerialMediationData S7 Class

Description

S7 class for serial mediation models where the effect flows through multiple mediators in sequence: X -> M1 -> M2 -> ... -> Mk -> Y.

This class supports serial mediation chains of any length, from simple two-mediator models (product-of-three: a * d * b) to complex chains with many mediators (product-of-k).

Usage

SerialMediationData(a_path, d_path, b_path, c_prime, estimates, vcov,
  sigma_mediators, sigma_y, treatment, mediators, outcome,
  mediator_predictors, outcome_predictors, data, n_obs, converged,
  source_package)

Arguments

a_path

Numeric scalar: effect of treatment on first mediator (X -> M1)

d_path

Numeric vector: sequential mediator-to-mediator effects

  • For 2 mediators (X -> M1 -> M2 -> Y): scalar d21 (M1 -> M2)

  • For 3 mediators (X -> M1 -> M2 -> M3 -> Y): c(d21, d32)

  • For k mediators: vector of length (k-1)

b_path

Numeric scalar: effect of last mediator on outcome (Mk -> Y)

c_prime

Numeric scalar: direct effect of treatment on outcome (X -> Y)

estimates

Numeric vector: all parameter estimates

vcov

Numeric matrix: variance-covariance matrix of estimates

sigma_mediators

Numeric vector or NULL: residual SDs for mediator models. Length should match number of mediators. First element is residual SD for M1 model, second element for M2 model, etc.

sigma_y

Numeric scalar or NULL: residual SD for outcome model

treatment

Character scalar: name of treatment variable

mediators

Character vector: names of mediators in sequential order. First element is M1, second element is M2, etc.

outcome

Character scalar: name of outcome variable

mediator_predictors

List of character vectors: predictor names for each mediator model. First list element contains predictors for M1 (typically just "X"), second element contains predictors for M2 (typically c("X", "M1")), etc.

outcome_predictors

Character vector: predictor names in outcome model

data

Data frame or NULL: original data

n_obs

Integer scalar: number of observations

converged

Logical scalar: whether all models converged

source_package

Character scalar: package/engine used for fitting

Details

Serial Mediation Structure

Serial mediation models the indirect effect flowing through a sequence of mediators. The indirect effect through the full chain is the product of the chain's path coefficients:

This is the effect through the chain only, and what nie() returns by default. Paths that skip a mediator (X -> M2, M1 -> Y, ...) are not part of it; nie(x, type = "total") adds them, and te() is the full total effect over every path, so pm() is the total indirect share of it. With treatment-by-mediator products in the outcome model, extract_mediation() returns a JointMediationData object with the effect through all the mediators together.

Path Notation

Extensibility

This class is designed to handle serial chains of any length:

Value

A SerialMediationData S7 object

Examples


# Two-mediator serial mediation (X -> M1 -> M2 -> Y)
# Product-of-three: a * d * b
serial_data <- SerialMediationData(
  a_path = 0.5,       # X -> M1
  d_path = 0.4,       # M1 -> M2 (scalar for 2 mediators)
  b_path = 0.3,       # M2 -> Y
  c_prime = 0.1,      # X -> Y (direct)
  estimates = c(0.5, 0.4, 0.3, 0.1),
  vcov = diag(4) * 0.01,
  sigma_mediators = c(1.0, 1.1),  # SD for M1, M2 models
  sigma_y = 1.2,
  treatment = "X",
  mediators = c("M1", "M2"),
  outcome = "Y",
  mediator_predictors = list(
    c("X"),           # M1 ~ X
    c("X", "M1")      # M2 ~ X + M1
  ),
  outcome_predictors = c("X", "M1", "M2"),  # Y ~ X + M1 + M2
  data = NULL,
  n_obs = 100L,
  converged = TRUE,
  source_package = "lavaan"
)

# Three-mediator serial mediation (X -> M1 -> M2 -> M3 -> Y)
# Product-of-four: a * d21 * d32 * b
serial_data_3 <- SerialMediationData(
  a_path = 0.5,           # X -> M1
  d_path = c(0.4, 0.35),  # M1 -> M2, M2 -> M3 (vector for 3 mediators)
  b_path = 0.3,           # M3 -> Y
  c_prime = 0.1,
  estimates = c(0.5, 0.4, 0.35, 0.3, 0.1),
  vcov = diag(5) * 0.01,
  sigma_mediators = c(1.0, 1.1, 1.05),  # SD for M1, M2, M3 models
  sigma_y = 1.2,
  treatment = "X",
  mediators = c("M1", "M2", "M3"),
  outcome = "Y",
  mediator_predictors = list(
    c("X"),              # M1 ~ X
    c("X", "M1"),        # M2 ~ X + M1
    c("X", "M1", "M2")   # M3 ~ X + M1 + M2
  ),
  outcome_predictors = c("X", "M1", "M2", "M3"),
  data = NULL,
  n_obs = 100L,
  converged = TRUE,
  source_package = "lavaan"
)



TwoLevelMediationData Class

Description

Experimental. This class, twolevel_statistic() and the level argument of the effect generics may change without the usual deprecation period (a two-level fitter in the sem engine, a later milestone, could change the object).

Usage

TwoLevelMediationData(
  a_within, b_within, c_prime_within, a_between, b_between, c_prime_between,
  estimates, vcov, parameter_table, treatment, mediator, outcome, cluster, n_obs,
  n_clusters, cluster_sizes, icc, between_identified, admissible, converged,
  cross_level_equal, fixed_paths, source, fixed_x, information, h1_information,
  se_type, estimator, missing, lavaan_version, call, between_parameterization,
  data, source_package, source_version
)

Arguments

a_within, b_within, c_prime_within

Numeric scalars: within-level paths (always finite).

a_between, b_between, c_prime_between

Numeric scalars: between-level paths; NA_real_ when between_identified is FALSE.

estimates

Named numeric vector of the identified path rows, in the order above.

vcov

Covariance matrix of estimates: the sub-block of the fit's joint covariance, so the cross-level covariances are carried.

parameter_table

Data frame, one row per path row (path, level, lhs, op, rhs, label, free, est, se), kept for audit.

treatment, mediator, outcome, cluster

Character scalars: variable names.

n_obs, n_clusters

Integer scalars: rows used and number of clusters.

cluster_sizes

Integer vector of cluster sizes (length n_clusters).

icc

Named numeric vector: intraclass correlation of treatment, mediator and outcome. It is the unrestricted (h1) estimate, the between variance over the total in the saturated two-level model (lavaan::lavInspect(fit, "icc") for a lavaan fit), not the ratio the fitted model implies; the within-only rule reads it.

between_identified

Logical scalar: whether the between level is identified.

admissible

Logical scalar: lavaan::lavInspect(fit, "post.check").

converged

Logical scalar: whether the fit converged.

cross_level_equal

Character vector: paths ("a", "b", "c_prime") equated across levels.

fixed_paths

Character vector: path rows with free == 0 (variance 0 in vcov).

source

Character scalar: "lavaan" or "native".

fixed_x, information, h1_information, se_type, estimator, missing

How the fit was made, read from it.

lavaan_version, call

Character scalars: provenance of the fit.

between_parameterization

Character scalar: "latent" (cluster means are latent).

data

Data frame or NULL: always NULL for the lavaan adapter (the fit is never refit and the data are not copied); kept for the contract shared with the other mediation classes, which read ⁠@data⁠.

source_package

Character scalar: "lavaan", or "medfit" for a native two-level fit; kept for the dependents contract shared with the other mediation classes (tests/testthat/test-dependents-contract.R pins it across classes).

source_version

Character: character(0) (the default) or one non-empty string, the version of the package that made the fit. The lavaan adapter stores the lavaan version here and in lavaan_version; lavaan_version may be character(0) for a fit lavaan did not make. Both are checked on construction and on assignment.

Details

S7 class for two-level mediation in which treatment, mediator and outcome are all measured on level-1 units nested in clusters (1-1-1), with the paths estimated separately at the within and the between level (latent cluster means, fixed slopes). Built by extract_mediation() from a lavaan two-level fit; the same class is the target of a sem engine fitter later (source says which).

Per level the indirect effect is NIE_l = a_l b_l, the direct effect is c'_l, and the contrast NIE_w - NIE_b is descriptive, not a test. When the between level cannot be identified (for example a treatment with no between-cluster variance) the object is within-only: the between properties are NA_real_ and the between rows are absent from estimates and vcov.

Value

A TwoLevelMediationData S7 object.

Examples


if (requireNamespace("lavaan", quietly = TRUE)) {
  set.seed(1)
  id <- rep(1:60, each = 5)
  xb <- stats::rnorm(60)[id]
  x <- xb + stats::rnorm(300)
  m <- 0.5 * x + stats::rnorm(60)[id] + stats::rnorm(300)
  y <- 0.4 * m + 0.2 * x + stats::rnorm(60)[id] + stats::rnorm(300)
  d <- data.frame(id = id, X = x, M = m, Y = y)
  model <- "
    level: 1
      M ~ X
      Y ~ M + X
    level: 2
      M ~ X
      Y ~ M + X
  "
  fit <- lavaan::sem(model, data = d, cluster = "id")
  td <- extract_mediation(fit, treatment = "X", mediator = "M", outcome = "Y")
  td@a_within * td@b_within
}



TwoLevelParallelMediationData Class

Description

Experimental. Like TwoLevelMediationData, this class may change without the usual deprecation period.

Usage

TwoLevelParallelMediationData(
  a_within, b_within, c_prime_within, a_between, b_between, c_prime_between,
  estimates, vcov, parameter_table, treatment, mediators, outcome, cluster, n_obs,
  n_clusters, cluster_sizes, icc, between_identified, admissible, converged,
  cross_level_equal, fixed_paths, source, fixed_x, information, h1_information,
  se_type, estimator, missing, lavaan_version, call, between_parameterization,
  data, source_package, source_version
)

Arguments

a_within, b_within

Named numeric vectors of length k (names mediators): within-level paths X \to M_j and M_j \to Y (always finite).

c_prime_within

Numeric scalar: within-level direct path (always finite).

a_between, b_between

Named numeric vectors of length k: between-level paths; all NA_real_ when between_identified is FALSE.

c_prime_between

Numeric scalar: between-level direct path; NA_real_ when between_identified is FALSE.

estimates

Named numeric vector of the identified path rows (the alias rows above).

vcov

Covariance matrix of estimates: the sub-block of the fit's joint covariance, so the cross-level and cross-mediator covariances are carried.

parameter_table

Data frame, one row per path row (path, level, lhs, op, rhs, label, free, est, se), kept for audit.

treatment, outcome, cluster

Character scalars: variable names.

mediators

Character vector of length k \ge 2: unique mediator names, in the order of the path vectors.

n_obs, n_clusters

Integer scalars: rows used and number of clusters.

cluster_sizes

Integer vector of cluster sizes (length n_clusters).

icc

Named numeric vector: intraclass correlation of the treatment, each mediator and the outcome. It is the unrestricted (h1) estimate, as for TwoLevelMediationData; the within-only rule reads it.

between_identified

Logical scalar: whether the between level is identified.

admissible

Logical scalar: lavaan::lavInspect(fit, "post.check").

converged

Logical scalar: whether the fit converged.

cross_level_equal

Character vector: paths equated across levels.

fixed_paths

Character vector: path rows with free == 0 (variance 0 in vcov).

source

Character scalar: "lavaan" or "native".

fixed_x, information, h1_information, se_type, estimator, missing

How the fit was made, read from it.

lavaan_version, call

Character scalars: provenance of the fit.

between_parameterization

Character scalar: "latent" (cluster means are latent).

data

Data frame or NULL: always NULL for the lavaan adapter.

source_package

Character scalar: "lavaan", or "medfit" for a native two-level fit.

source_version

Character: character(0) (the default) or one non-empty string, the version of the package that made the fit.

Details

S7 class for two-level mediation with k \ge 2 parallel mediators, all measured on level-1 units nested in clusters (1-1-1), with the paths estimated separately at the within and the between level (latent cluster means, fixed slopes). It is the parallel counterpart of TwoLevelMediationData: a separate class, so the one-mediator object keeps its scalar paths. Every property other than the paths and mediators has the meaning it has there.

Per level l the specific indirect effect through M_j is a_{jl} b_{jl}, the total indirect effect is \sum_j a_{jl} b_{jl} and the direct effect is c'_l. When the between level cannot be identified the object is within-only: the between path vectors hold NA_real_ (still named by mediators), c_prime_between is NA_real_, and the between rows are absent from estimates and vcov.

The alias rows of estimates and vcov are, per level, ⁠a_<M>_within⁠ for each mediator, then ⁠b_<M>_within⁠, then c_prime_within, and the same set with ⁠_between⁠.

Value

A TwoLevelParallelMediationData S7 object.


Perform Bootstrap Inference for Mediation Statistics

Description

Conduct bootstrap inference to compute confidence intervals for mediation statistics. Supports parametric, nonparametric, and plugin methods.

Usage

bootstrap_mediation(
  statistic_fn,
  method = c("parametric", "nonparametric", "plugin"),
  mediation_data = NULL,
  data = NULL,
  n_boot = 1000L,
  ci_level = 0.95,
  parallel = FALSE,
  ncores = NULL,
  seed = NULL,
  cluster = NULL,
  ...,
  source_fit = NULL,
  effect = NULL
)

Arguments

statistic_fn

Function that computes the statistic of interest.

  • For parametric bootstrap: receives named parameter vector, returns scalar

  • For nonparametric bootstrap: receives data frame, returns scalar

  • For plugin: receives named parameter vector, returns scalar Omit this argument when supplying source_fit.

method

Character string: bootstrap method. Options:

  • "parametric": Sample from multivariate normal (fast, assumes normality)

  • "nonparametric": Resample data and refit (robust, slower)

  • "plugin": Point estimate only, no CI (fastest)

mediation_data

A mediation data object (required for parametric/plugin): MediationData, SerialMediationData, ParallelMediationData, InteractionMediationData, JointMediationData, TwoLevelMediationData or TwoLevelParallelMediationData (see twolevel_statistic()). statistic_fn receives its named ⁠@estimates⁠ vector, which includes path aliases (e.g. a, d1, b, c_prime for a serial chain; a1, b1, a2, b2 for parallel mediators). For a JointMediationData the aliases alone cannot reproduce the NDE, which also needs the prefixed intercept and covariate rows (m1_, ..., y_) and the sample covariate means.

data

Data frame (required for nonparametric bootstrap)

n_boot

Integer: number of bootstrap samples (default: 1000)

ci_level

Numeric: confidence level between 0 and 1 (default: 0.95)

parallel

Logical: use parallel processing? (default: FALSE)

ncores

Integer: number of cores for parallel processing. If NULL, uses parallel::detectCores() - 1

seed

Integer: random seed for reproducibility (optional but recommended)

cluster

Character string: name of a cluster variable in data, for method = "nonparametric" only (an error with the other methods). The resampling then draws whole clusters with replacement and gives each draw a fresh cluster id before statistic_fn sees the data, so a cluster drawn twice is refit as two clusters, not one bigger one. Singular fits and convergence warnings from a refit count as failures: they are excluded, their messages are suppressed, and their number is added to the warning. NULL (default) resamples rows as before.

...

Additional arguments (reserved for future use); must be empty with source_fit.

source_fit

Optional accepted bounded FIML SEMFit, supplied by name. Its original incomplete retained records, model and settings are authoritative. Omit statistic_fn, mediation_data, data and cluster with this route.

effect

Scalar unstandardized effect, exactly "nie", "nde" or "te", required with source_fit and unavailable without it. Supplied by name.

Details

Bounded FIML source intervals (unavailable pending admission)

Unavailable. While statistical admission is undecided, every non-NULL source_fit is refused before any other check, random draw, refit or worker, with a classed error (medfit_error_fiml_inference_unavailable). No option or environment variable enables it. The text below records the implemented design and is not a statement that the intervals are supported.

Supply source_fit and effect by name and choose method explicitly. Only accepted three-variable Gaussian random-X simple mediation fits from fit_sem() are supported, with the direct path free or fixed exactly at zero. This route does not support callbacks, plugin estimates, clusters or additional arguments. Fits with one or two covariates (including two parallel mediators with covariates) are refused with medfit_error_fiml_covariate_source_fit, and fits with two parallel mediators and no covariates with medfit_error_fiml_parallel_source_fit (both checks follow the withheld-inference guard above). Bounded FIML objects supplied as mediation_data or data remain refused. Object-aware guards run before package-controlled RNG, workers or refits; opaque user callbacks and external-first dispatch are outside that guarantee.

method = "nonparametric" gives a retained-row FIML percentile interval: resample entire nonempty records at fixed retained N, preserving missingness and duplicate rows, and refit the identical model with the accepted source protocol. method = "parametric" gives a Gaussian parameter-draw percentile interval, not a synthetic-data bootstrap: jointly draw the canonical free parameters using the full observed/model covariance in original coordinates, without refitting. The symmetric correlation-root factor permits only roundoff repairs; materially asymmetric or indefinite covariance is refused. Fixed zeros stay exact. Negative nuisance-variance draws are not filtered or truncated before evaluating the effect.

Both routes retain the original fitted effect as the point estimate and use type-7 empirical quantiles. Every requested replicate is recorded in ⁠@inference⁠ (schema fiml-bootstrap-1), including indices or draw IDs, reasons, source/RNG provenance and retained/collected counts. Any failed, invalid or nonfinite required replicate withholds the entire interval. Interruption returns an incomplete length-n_boot result with interrupted/unattempted IDs and NA unresolved values. Print, summary, tidy and changed-level confint() cannot report a survivor interval; tidy distribution SD is also unavailable for withheld results. An all-success SD is descriptive, not a robust standard error.

The target is conditional on retained nonempty records. Assumptions include IID jointly Gaussian data, ignorable MAR with distinct missingness/model parameters, positivity and identified information. Retention normalization must be independent of model parameters; independently empty MCAR records suffice. Arbitrary value-dependent empty-row deletion and MNAR are not covered. Numerical verification does not establish interval coverage; statistical admission remains deferred. See the Methods and Formulas article, Bounded FIML, for the mathematical definition. These source intervals are development code added after 0.16.0 and are withheld.

Bootstrap Methods

Parametric Bootstrap (method = "parametric"):

Nonparametric Bootstrap (method = "nonparametric"):

Plugin Estimator (method = "plugin"):

Statistic Function

The statistic_fn should be a function that:

Common statistic functions for indirect effect:

# Using parameter names from MediationData
indirect_fn <- function(theta) {
  theta["m_X"] * theta["y_M"]
}

Parallel Processing

Set parallel = TRUE to use multiple cores:

Reproducibility

Always set a seed for reproducible results:

bootstrap_mediation(..., seed = 12345)

A fixed seed gives the same resamples for any ncores, and for sequential runs, because every resample is drawn before the work is split across cores. This holds for the nonparametric and cluster methods (earlier versions drew inside each worker). The statistic is still computed in the workers, so a statistic_fn that uses random numbers itself is not covered (in a sequential run its draws now follow all the resampling draws instead of interleaving with them, so its stream differs from earlier versions), and floating-point results can differ in the last digits when BLAS threads differ. The resamples are held in memory before the refits start: n_boot integer vectors of length n (about 4 * n * n_boot bytes; 800 MB for n = 100000 and n_boot = 2000).

Value

A BootstrapResult object containing:

See Also

BootstrapResult, MediationData, fit_mediation()

Examples

# Fit mediation model
med_data <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)

# Define indirect effect function
indirect_fn <- function(theta) theta["m_treatment"] * theta["y_mediator1"]

# Plugin estimator (point estimate only, fastest)
result_plugin <- bootstrap_mediation(
  statistic_fn = indirect_fn,
  method = "plugin",
  mediation_data = med_data
)
print(result_plugin)


# Parametric bootstrap (recommended for most applications)
result <- bootstrap_mediation(
  statistic_fn = indirect_fn,
  method = "parametric",
  mediation_data = med_data,
  n_boot = 1000,
  ci_level = 0.95,
  seed = 12345
)
print(result)

# Nonparametric bootstrap (slower but more robust)
refit_fn <- function(boot_data) {
  fit_m <- lm(mediator1 ~ treatment + covariate1 + covariate2,
              data = boot_data)
  fit_y <- lm(outcome ~ treatment + mediator1 + covariate1 + covariate2,
              data = boot_data)
  unname(coef(fit_m)["treatment"] * coef(fit_y)["mediator1"])
}

result_np <- bootstrap_mediation(
  statistic_fn = refit_fn,
  method = "nonparametric",
  data = mediation_demo,
  n_boot = 500,
  seed = 12345
)
print(result_np)



if (requireNamespace("lme4", quietly = TRUE)) {
# Treatment assigned to whole clusters (needs lme4); formulas hold fixed
# effects only, the engine adds the random cluster intercept
set.seed(1)
J <- 30
id <- rep(seq_len(J), each = 6)
cdat <- data.frame(school = factor(id), X = sample(rep(0:1, J / 2))[id])
cdat$M <- 0.5 * cdat$X + rnorm(J, sd = 0.5)[id] + rnorm(J * 6)
cdat$Y <- 0.2 * cdat$X + 0.4 * cdat$M + rnorm(J, sd = 0.5)[id] + rnorm(J * 6)
# Resample whole clusters. A refit that is singular or does not converge is
# dropped, and the warning counts how many were
nie_of <- function(d) {
  unname(nie(fit_mediation(Y ~ X + M, M ~ X, data = d, treatment = "X",
                           mediator = "M", engine = "lmer",
                           cluster = "school")))
}
result_cluster <- bootstrap_mediation(
  nie_of, method = "nonparametric", data = cdat, cluster = "school",
  n_boot = 20, seed = 1
)
print(result_cluster)
}



Compare medfit's Product-Null LR with OpenMx or lavaan

Description

Bounded FIML fits are refused before an external-engine comparison or refit; this function does not extend their supported inference. See fit_sem().

Runs the likelihood-ratio test of a product null (a b = 0) in an external SEM engine and compares it with medfit's own mbco_sem() statistic. A general-purpose optimizer handed the nonlinear constraint a b = 0 can drop it (OpenMx at a zero start) or stop at the wrong branch (lavaan from either start, OpenMx from its default start), which reports a statistic above the true minimum. compare_lr() flags exactly those cases and nothing else.

A warning is raised only on observed evidence, never because an LR is zero: medfit_warning_engine_constraint_dropped when the engine's returned fit violates the product constraint, and medfit_warning_engine_statistic_above_max when the engine's statistic exceeds medfit's. Both inherit from medfit_warning_engine_comparison. If medfit has no accepted reference, the engines' unrestricted fits differ from medfit's, or a run fails or cannot be checked, the verdict is "unresolved" and neither side is blamed. medfit has no accepted reference when one of its own refits cannot be fitted (see mbco_sem()): the reference LR is then NA and the result is a comparison with that verdict, not an error.

Only observed-variable models are compared. With either engine, a saturated mean structure (every intercept free) and fixed_x (all, a named subset or a lenient subset) are supported: the fixed exogenous moments are written to the engine as fixed parameters at their sample values (in OpenMx, a fit with a mean structure is run on the raw data the fit used). Latent variables, product terms, fixed or constrained intercepts, weights, factors, other fixed or shared parameters, start/bound modifiers and constraints in the model are refused by name.

Known limit (#320): an engine's statistic can land above medfit's reference because the null a b = 0 is two lines, a = 0 and b = 0, each with its own minimum. A general-purpose optimizer settles on one line; when it settles on the line with the larger minimum, the engine's statistic is that line's LR, not the product-null LR. medfit fits each line as a linear model and keeps the smaller (see mbco_sem()). medfit_warning_engine_statistic_above_max says only that a feasible, converged engine statistic exceeds the reference; it does not say which line the engine reached or whether it reached that line's minimum. A run that stopped short of the minimum on either line raises the same warning. Treat the warning as undiagnosed until both line minima are computed: if the engine's statistic equals the other line's minimum, the engine chose the wrong line and medfit's reference stands; otherwise it may be an optimizer failure in the engine. On the pinned design (15 seeds by 4 cells, 60 runs per engine) the warning fires in 18 of 60 lavaan runs (either start) and 13 of 60 OpenMx default-start runs; in that design each of those runs was checked and equals the other line's minimum, and the smaller of lavaan's two runs equals medfit's reference in all 60. The counts are unchanged by the 0.15.0 flip of the fit_sem() defaults, and no run is mislabeled.

Usage

compare_lr(object, paths, engine = c("lavaan", "openmx"), tolerance = 1e-04)

Arguments

object

A SEMFit from fit_sem().

paths

Character vector: the labels of the regression paths whose product is the indirect effect, as in mbco_sem().

engine

"lavaan" or "openmx": the external comparison program that runs the product-null LR for comparison, not a fitter of the mediation model. The mediation model is always medfit's native fit object, and the result's reference is medfit's LR. The package must be installed.

tolerance

Relative tolerance on the LR difference, scaled by max(1, LR). Default 1e-4; values above 1e-2 are refused, because a loose tolerance would call different statistics equal.

Value

An object of class medfit_lr_comparison: a list with verdict ("agree", "disagree" or "unresolved"), reason, reference (medfit's LR, NA when it has none, and whether it was accepted), runs (one row per engine start with the LR, convergence, constraint residual and status) and engine.

See Also

mbco_sem(), fit_sem()

Examples


if (requireNamespace("lavaan", quietly = TRUE)) {
  fit <- fit_sem(
    "mediator1 ~ a*treatment\noutcome ~ b*mediator1 + cp*treatment",
    data = mediation_demo, fixed_x = FALSE, meanstructure = NULL
  )
  compare_lr(fit, paths = c("a", "b"), engine = "lavaan")
}


Decomposition of a Mediation Effect

Description

Return the components of the total effect for an object whose outcome model has treatment-by-mediator products.

For an InteractionMediationData object this is VanderWeele's (2014) four-way decomposition: controlled direct effect (CDE), reference interaction (INTref), mediated interaction (INTmed), and pure indirect effect (PIE), together with the derived natural direct and indirect effects and the total effect. For a JointMediationData object it is the CDE and the joint natural direct and indirect effects (VanderWeele and Vansteelandt 2014).

Usage

decompose(x, ...)

Arguments

x

An InteractionMediationData or JointMediationData object.

...

Additional arguments (ignored).

Details

For a 0/1 treatment, outcome model Y = \theta_0 + \theta_1 X + \theta_2 M + \theta_3 X M + \dots, mediator model M = \beta_0 + \beta_1 X + \dots, and reference mediator level m^*:

CDE = \theta_1 + \theta_3 m^*

INTref = \theta_3 (E[M \mid X = 0, \bar c] - m^*)

INTmed = \theta_3 \beta_1

PIE = \theta_2 \beta_1

with NDE = CDE + INTref, NIE = INTmed + PIE, and TE = NDE + NIE. E[M \mid X = 0, \bar c] is the mediator model's prediction at no treatment and the covariate means.

Value

A named numeric vector: c(cde, int_ref, int_med, pie, nde, nie, total) for InteractionMediationData, c(cde, nde, nie, total) for JointMediationData.

References

VanderWeele, T. J. (2014). A unification of mediation and interaction: A 4-way decomposition. Epidemiology, 25(5), 749–761.

VanderWeele, T. J., & Vansteelandt, S. (2014). Mediation analysis with multiple mediators. Epidemiologic Methods, 2(1), 95–115. doi:10.1515/em-2012-0010

See Also

nie(), nde(), te()

Examples


fit_m <- lm(mediator1 ~ treatment + covariate1 + covariate2,
            data = mediation_demo)
fit_y <- lm(outcome ~ treatment * mediator1 + covariate1 + covariate2,
            data = mediation_demo)
med_int <- extract_mediation(fit_m, model_y = fit_y,
                             treatment = "treatment", mediator = "mediator1")
decompose(med_int)



Extract Mediation Structure from Fitted Models

Description

Generic function to extract mediation structure (a, b, c' paths and variance-covariance matrices) from fitted models. This function provides a unified interface for extracting mediation information from various model types (lm, glm, lavaan, lmer, and a SEMFit from the sem engine).

Usage

extract_mediation(object, ...)

Arguments

object

Fitted model object (lm, glm, lavaan, lmerMod, or a SEMFit)

...

Additional arguments passed to methods. Common arguments include:

  • treatment: Character string specifying treatment variable name

  • mediator: Character string specifying mediator variable name

  • Method-specific arguments (see individual method documentation)

Details

The extract_mediation() generic provides methods for different model types:

Note: OpenMx extraction is planned for a future release.

The returned objects share one interface (nie(), nde(), te(), confint(), bootstrap_mediation(), ...) for use by other medfit functions and dependent packages (probmed, RMediation, medrobust).

The class returned depends on the structure. A single mediator gives a MediationData object, or an InteractionMediationData object when the outcome model has a treatment-by-mediator term. A mediator vector of length two or more gives a SerialMediationData or ParallelMediationData object; for lm/glm fits whose outcome model has a treatment-by-mediator term written with : or *, it gives a JointMediationData object with the joint natural effects of the mediators. Any other product term in a multi-mediator fit errors.

Arguments for lm and glm models

With object the fitted mediator model (the first mediator's model for several mediators), the lm/glm method takes:

The lavaan method takes a fitted lavaan model and the variable names; see ?extract_mediation_lavaan for its arguments.

Covariance of the estimates

For lm/glm fits, each equation's block of ⁠@vcov⁠ is that model's own covariance. The blocks for different equations are stored as zero. This is exact for simple mediation, serial chains, and the four-way model, whose later equations contain every regressor of the earlier ones, but for parallel mediators it leaves out the covariance between their a paths. JointMediationData stores the full stacked least-squares covariance, and a lavaan fit estimates all equations jointly, so for the same data the intervals can differ between engines.

The four-way effects that contain a covariate mean (int_ref, the NDE and the total effect) treat that mean as a fixed constant, so their standard errors and intervals are conditional on the observed covariates. They omit the sampling variance of the estimated mean, theta3 * gamma times the variance of the covariate mean, so they can understate the uncertainty of a population-average effect. CDE, int_med, PIE and the NIE do not depend on the mean. For population-average standard errors set options(medfit.covariate_mean_variance = TRUE): tidy() and confint() then add the variance of the estimated covariate mean, (theta3 * gamma)^2 times the variance of the covariate mean (case-weighted when the fit has weights), to int_ref, the NDE and the total effect; the default stays conditional, as lavaan's ⁠:=⁠ and the glm route are. Or resample rows with bootstrap_mediation() (method = "nonparametric").

Coefficient names

The simple single-mediator MediationData from lm/glm fits names three coefficients ⁠m_<treatment>⁠, ⁠y_<mediator>⁠ and ⁠y_<treatment>⁠ (m_X, y_M and y_X for variables X and M), and code that looks coefficients up by name, such as the parametric bootstrap in probmed, relies on them. The lavaan method adds the same three names to ⁠@estimates⁠ and ⁠@vcov⁠ for an observed, continuous treatment, mediator and outcome. Each is a second name for the a, b or c_prime path, with the same estimate and covariances, appended after the existing rows. A lavaan fit with a latent or ordered treatment, mediator or outcome, and any extraction with standardized = TRUE, gets none of the three and works with the plugin estimators only. Serial, parallel and four-way objects are not affected.

Value

An S7 object whose class depends on the mediation structure (see Details): MediationData, InteractionMediationData, SerialMediationData, ParallelMediationData, JointMediationData, or ClusterMediationData. Each carries the path coefficients, the full parameter vector and its variance-covariance matrix, residual standard deviations (for Gaussian models), variable names, and the original data when available.

See Also

MediationData, fit_mediation(), bootstrap_mediation()

Examples


# Extract the mediation structure from fitted lm models, using the
# simulated mediation_demo data bundled with medfit
fit_m <- lm(mediator1 ~ treatment + covariate1 + covariate2,
            data = mediation_demo)
fit_y <- lm(outcome ~ treatment + mediator1 + covariate1 + covariate2,
            data = mediation_demo)
med_data <- extract_mediation(fit_m, model_y = fit_y,
                              treatment = "treatment", mediator = "mediator1")



if (requireNamespace("lme4", quietly = TRUE)) {
# Treatment assigned to whole clusters (needs lme4); formulas hold fixed
# effects only, the engine adds the random cluster intercept
set.seed(1)
J <- 30
id <- rep(seq_len(J), each = 6)
cdat <- data.frame(school = factor(id), X = sample(rep(0:1, J / 2))[id])
cdat$M <- 0.5 * cdat$X + rnorm(J, sd = 0.5)[id] + rnorm(J * 6)
cdat$Y <- 0.2 * cdat$X + 0.4 * cdat$M + rnorm(J, sd = 0.5)[id] + rnorm(J * 6)
# The outcome model carries the mediator as its within-cluster deviation
# plus the observed cluster mean
cdat$M_bar <- ave(cdat$M, cdat$school)
cdat$M_w <- cdat$M - cdat$M_bar
fit_m <- lme4::lmer(M ~ X + (1 | school), data = cdat)
fit_y <- lme4::lmer(Y ~ X + M_w + M_bar + (1 | school), data = cdat)
cluster_med <- extract_mediation(fit_m, model_y = fit_y, treatment = "X",
                                 mediator = "M", cluster = "school")
nie(cluster_med)
}



Extract Mediation Structure from lavaan Model

Description

Internal function for extracting mediation structure from lavaan models. This function is registered as an S7 method in .onLoad() when lavaan is available.

Usage

extract_mediation_lavaan(
  object,
  treatment,
  mediator,
  outcome = NULL,
  a_label = "a",
  b_label = "b",
  cp_label = "cp",
  standardized = FALSE,
  structure = c("auto", "serial", "parallel"),
  decomposition = c("auto", "four_way", "two_way"),
  interaction = NULL,
  m_star = 0,
  ...
)

Arguments

object

Fitted lavaan model object

treatment

Character: name of the treatment variable

mediator

Character: name of the mediator variable for simple mediation (X -> M -> Y), OR an ordered character vector of length >= 2 for serial mediation (X -> M1 -> M2 -> ... -> Y). When a vector is supplied the function returns a SerialMediationData object instead of MediationData.

outcome

Character: name of the outcome variable (optional, auto-detected)

a_label

Character: label for the a path in lavaan model (default: "a")

b_label

Character: label for the b path in lavaan model (default: "b")

cp_label

Character: label for the c' path in lavaan model (default: "cp")

standardized

Logical: extract standardized coefficients? (default: FALSE)

structure

Character: one of "auto" (default), "serial", or "parallel". Selects the multi-mediator structure when mediator has length >= 2. "auto" infers it from the SEM's regression rows: a mediator regressed on another mediator implies "serial", otherwise "parallel". The explicit values are authoritative and skip detection.

decomposition

Character: "auto" (default) uses the four-way decomposition when a single mediator's outcome equation has a treatment-by-mediator product; "four_way" requires that product; "two_way" ignores it.

interaction

Optional character: name of the product column in the outcome equation (lavaan takes the product as a data column). When NULL, treatment:mediator and mediator:treatment are tried.

m_star

Numeric scalar: reference mediator level for the controlled direct effect in the four-way decomposition (default 0).

...

Additional arguments (ignored)

Details

This method extracts mediation structure from a fitted lavaan SEM model. The lavaan model should specify labeled paths for the mediation structure.

Typical lavaan Model Specification

model <- "
  # Mediator model
  M ~ a*X

  # Outcome model
  Y ~ b*M + cp*X

  # Indirect and total effects (optional)
  indirect := a*b
  total := cp + a*b
"

Path Labels

By default, the function looks for paths labeled:

You can customize these labels using the a_label, b_label, and cp_label arguments.

Alternative: Unlabeled Paths

If paths are not labeled, the function will attempt to identify them by variable names. This requires specifying treatment, mediator, and outcome arguments.

Value

A MediationData object; an InteractionMediationData object when a single mediator's outcome equation has a treatment-by-mediator product; a SerialMediationData object when mediator is a length >= 2 vector resolving to a serial chain; or a ParallelMediationData object when it resolves to parallel mediation.

Limits

A two-level fit (lavaan::sem(..., cluster = ) with ⁠level:⁠ blocks) returns a TwoLevelMediationData object with the a, b and c' paths at the within and the between level (linear paths, no products, standardized = FALSE); see that class for the identification rules. Two or more mediators return a TwoLevelParallelMediationData object (experimental); serial mediators, a covariate passed as a mediator, and duplicate or overlapping roles are refused with medfit_error_twolevel_unsupported. Fits with more than two levels are refused with the classed error medfit_error_lavaan_multilevel; extraction would otherwise read the within level only. Multigroup fits (⁠group =⁠) are refused with medfit_error_lavaan_multigroup; extraction would otherwise return the first group's paths with the total sample size.

Examples


if (requireNamespace("lavaan", quietly = TRUE)) {
  # Simulate a simple mediation data set (X -> M -> Y)
  set.seed(123)
  n <- 200
  X <- rnorm(n)
  M <- 0.5 * X + rnorm(n)
  Y <- 0.3 * M + 0.2 * X + rnorm(n)
  dat <- data.frame(X = X, M = M, Y = Y)

  # Fit a labeled lavaan mediation model
  model <- "
    M ~ a*X
    Y ~ b*M + cp*X
  "
  fit <- lavaan::sem(model, data = dat)

  # Extract the mediation structure (dispatches to the lavaan method)
  med_data <- extract_mediation(
    fit,
    treatment = "X",
    mediator = "M",
    outcome = "Y"
  )
}



Fit Mediation Models

Description

Fit mediation models using a specified modeling engine. This function provides a convenient formula-based interface for fitting both the mediator and outcome models simultaneously.

Usage

fit_mediation(
  formula_y,
  formula_m,
  data,
  treatment,
  mediator,
  engine = "glm",
  family_y = stats::gaussian(),
  family_m = stats::gaussian(),
  weights = NULL,
  se_type = c("model", "sandwich", "kr"),
  engine_args = list(),
  m_star = 0,
  cluster = NULL,
  model = NULL,
  ...
)

Arguments

formula_y

Formula for outcome model (e.g., Y ~ X + M + C). Not used with engine = "sem", which takes model instead.

formula_m

Formula for mediator model (e.g., M ~ X + C). Not used with engine = "sem".

data

Data frame containing all variables. With the "glm" engine, rows with a missing value on any variable in either formula are dropped before fitting, so both models share one sample; nobs() and ⁠@n_obs⁠ count the rows kept. Row-level arguments (weights and, in ..., subset, offset, etastart and mustart) refer to the rows of data as passed: they are applied to those rows first, then incomplete rows are dropped.

treatment

Character string: name of treatment variable

mediator

Character string: name of mediator variable

engine

Character string: modeling engine to use. Currently supports:

  • "glm": Generalized linear models (default)

  • "regmedint": Closed-form regression-based (in)direct effects via the suggested regmedint package (VanderWeele's regression approach, with optional treatment-mediator interaction)

  • "sem": the sem engine, medfit's own maximum-likelihood SEM fitter, fitted from model syntax given as model (see fit_sem()). "native" is the legacy spelling of the same engine and is still accepted. The fit is then extracted with extract_mediation(). Supports observed and latent mediators, equality and inequality constraints, and ⁠:=⁠ parameters. Case weights and se_type = "sandwich" map to fit_sem()'s weights (weighted maximum likelihood) and its robust sandwich covariance.

  • "lmer": Linear mixed models for a treatment assigned to whole clusters (the 2-1-1 design), via the suggested lme4 package; needs ⁠cluster =⁠ and returns a ClusterMediationData. The engine drops incomplete rows once, splits the mediator and each level-1 covariate into its within-cluster deviation and observed cluster mean (⁠<M>_cwc⁠, ⁠<M>_cm⁠), adds a random cluster intercept to both models, and fits by REML. The formulas hold fixed effects only (a random-effect term such as (1 | id) is an error; random slopes go in engine_args). It does not take weights, non-Gaussian families, se_type = "sandwich", or extra arguments.

family_y

Family object for outcome model (default: gaussian())

family_m

Family object for mediator model (default: gaussian())

weights

Optional numeric vector of case weights (length nrow(data)), passed to both the mediator and outcome stats::glm() fits. Use for inverse-probability weighting (IPW). NULL (default) fits unweighted.

se_type

Variance-covariance estimator for ⁠@vcov⁠: "model" (default, model-based stats::vcov) or "sandwich" (heteroskedasticity-consistent sandwich::vcovHC, type HC3, recommended for IPW-weighted fits). The "sandwich" option requires the suggested sandwich package. With engine = "lmer" only, "kr" uses the Kenward-Roger adjusted covariance and stores a degrees of freedom for each path, so the path intervals are t intervals; it needs REML fits and the suggested pbkrtest package. With engine = "sem", "sandwich" is the HC0-type robust covariance (see fit_sem()), which is smaller than the glm engine's HC3 by a factor that shrinks like 1/n.

engine_args

Named list of engine-specific overrides (default: list(), no overrides). Ignored by engine = "glm". For engine = "sem", recognized names are information, n_starts, meanstructure, fixed_x, missing and control (passed to fit_sem(), whose defaults for fixed_x and meanstructure changed in 0.15.0) and outcome, structure, decomposition, interaction, a_label, b_label and cp_label (passed to extract_mediation()); any other name is an error. Bounded FIML requires engine_args = list(missing = "fiml", fixed_x = FALSE) and the settings/limits in fit_sem(); se_type = "model" stays at the top level. Listwise defaults and the other engines' missing-data behavior are unchanged. For engine = "lmer", recognized names are random_y and random_m (one-sided formulas of level-1 terms that get correlated random slopes; ~ M in random_y is applied to the within-cluster mediator term) and REML (default TRUE); any other name is an error. For engine = "regmedint", recognized names are interaction, cvar, mreg, yreg, a0, a1, and c_cond; each replaces the value the adapter would otherwise derive from the formulas, families, and data. The reference mediator level is set with m_star, not here.

m_star

Numeric scalar: reference mediator level m^* at which the controlled direct effect is evaluated (default: 0). Used only when formula_y carries a treatment-by-mediator term, i.e. when the returned object is an InteractionMediationData. Supplying it for a fit that has no such term is an error rather than a silent no-op. That check keys on whether the argument was given at the call site, not on whether it differs from the default, so a wrapper that forwards m_star unconditionally will trigger it on two-way fits; forward it only when its own caller supplied one.

cluster

Character string: name of the cluster variable in data. Required with engine = "lmer"; with engine = "sem" it is passed to fit_sem() for a two-level model (experimental, see its cluster argument); an error with the other engines.

model

Character string: model syntax for engine = "sem" (required there, an error with any other engine). treatment and mediator name variables in the syntax; a latent mediator need not be a column of data. Because model is a named argument, an argument passed to stats::glm() through ... that partially matches it (mod = FALSE) now binds here and is an error with the glm engine; drop it, since glm()'s own model argument cannot be passed through.

...

Additional arguments passed to the fitting function. With the "glm" engine, subset (evaluated in the calling frame), offset, etastart and mustart describe the rows of data as passed, so a vector must have length nrow(data); incomplete rows are dropped after they are applied. Each is evaluated in the calling frame, not inside data, and is passed to both the mediator and outcome models.

Details

Model Specification

The function fits two models:

  1. Mediator model: formula_m (e.g., M ~ X + C1 + C2)

  2. Outcome model: formula_y (e.g., Y ~ X + M + C1 + C2)

The treatment variable must appear in both formulas. The mediator variable must appear in the outcome formula but NOT in the mediator formula (as it is the response).

GLM Engine

When engine = "glm" (default):

Common Family Specifications

regmedint Engine

When engine = "regmedint":

Reference Mediator Level

When the fit yields an InteractionMediationData, m_star fixes the level m^* at which the controlled direct effect is read off: CDE = \theta_1 + \theta_3 m^* and INTref = \theta_3 (E[M \mid X = 0] - m^*). The two shift in compensating directions, so nde(), nie(), te(), and pm() are invariant to m_star; only the CDE/INTref split moves.

The engines reach the same result by different routes. engine = "glm" applies m_star at extraction time, after the coefficients are fit; engine = "regmedint" passes it to regmedint::regmedint() as m_cde, where it is consumed by that package's closed-form estimator at fitting time. Supplying m_star for a fit with no treatment-by-mediator term is an error, not a silent no-op.

Value

A MediationData object containing the fitted mediation structure, or an InteractionMediationData object when formula_y contains a treatment-by-mediator interaction term.

References

VanderWeele, T. J. (2014). A unification of mediation and interaction: A 4-way decomposition. Epidemiology, 25(5), 749–761.

See Also

MediationData, extract_mediation(), bootstrap_mediation()

Examples

# mediation_demo is simulated data bundled with medfit; its covariates
# confound the mediator-outcome relation, so both models adjust for them
med_data <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)
print(med_data)


# Binary outcome (takes longer to fit): dichotomize the outcome at its median
demo <- mediation_demo
demo$outcome_bin <- as.integer(demo$outcome > stats::median(demo$outcome))
med_data_bin <- fit_mediation(
  formula_y = outcome_bin ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = demo,
  treatment = "treatment",
  mediator = "mediator1",
  family_y = binomial()
)



if (requireNamespace("lme4", quietly = TRUE)) {
# Treatment assigned to whole clusters (needs lme4); formulas hold fixed
# effects only, the engine adds the random cluster intercept
set.seed(1)
J <- 30
id <- rep(seq_len(J), each = 6)
cdat <- data.frame(school = factor(id), X = sample(rep(0:1, J / 2))[id])
cdat$M <- 0.5 * cdat$X + rnorm(J, sd = 0.5)[id] + rnorm(J * 6)
cdat$Y <- 0.2 * cdat$X + 0.4 * cdat$M + rnorm(J, sd = 0.5)[id] + rnorm(J * 6)
cluster_fit <- fit_mediation(
  Y ~ X + M, M ~ X, data = cdat,
  treatment = "X", mediator = "M",
  engine = "lmer", cluster = "school"
)
nie(cluster_fit)       # a * b_between
decompose(cluster_fit) # own-mediator and spillover parts
}



Fit a Structural Equation Model by Maximum Likelihood

Description

Fits a model written in lavaan-style syntax to raw data with the sem engine, medfit's own maximum-likelihood SEM fitter, and returns a SEMFit object. The engine handles observed and latent variables, user labels, fixed values, starts and bounds, equality and inequality constraints (==, <, >, linear or nonlinear), and defined parameters (⁠:=⁠) with delta-method standard errors.

Usage

fit_sem(
  model,
  data,
  information = c("observed", "expected"),
  n_starts = NULL,
  control = list(),
  weights = NULL,
  se_type = c("model", "sandwich"),
  meanstructure = TRUE,
  fixed_x = TRUE,
  sampling_weights = lifecycle::deprecated(),
  missing = c("listwise", "fiml"),
  cluster = NULL,
  estimator = c("ML", "MLR")
)

Arguments

model

Character: model syntax. Lines may use ~ (regression), ⁠=~⁠ (latent variable), ⁠~~⁠ (variance or covariance), label*variable modifiers, start(), lower() and upper(), and the constraint operators ==, <, > and ⁠:=⁠. An intercept is written y ~ 1 (alone or with other terms, as in y ~ 1 + x) and turns on the mean structure. A product of two observed variables is written x:m on the right side of a regression (canonical name m:x); ?"medfit-syntax" lists the supported class and each limit.

data

A data frame with the model's observed variables. Numeric columns are used as is; a factor, character or logical column named on a regression's right side is expanded to 0/1 dummies (?"medfit-syntax" lists the rules and limits). Rows with missing values in those columns are dropped once (listwise deletion) and counted in n_dropped under the default missing = "listwise". Bounded missing = "fiml" accepts numeric model columns only, retains rows with any observed model variable, and drops only all-empty model rows; extra columns do not select rows.

information

Character: "observed" (default) or "expected" information for the standard errors. "expected" is an error for a model with a product term that has an endogenous factor (the product is a function of another variable, so the expected information gives wrong standard errors); use the default with se_type = "sandwich". Bounded FIML supports only "observed".

n_starts

Positive integer or NULL: number of optimizer starts tried before the fit is declared failed (NULL uses 5). Retries use perturbed starts drawn under a fixed seed and never change the caller's random number stream; with 3 or more starts the last attempt is the model's own moment-based start, so a start in a bad basin does not end the fit. With a nonlinear constraint, which can leave several local optima, every start is tried and the best accepted one is kept (a warning says when the accepted starts disagree); otherwise the first accepted start is used. A supported nonzero-product equality searches both sign branches independently, with n_starts starts per nonempty branch; aggregate diagnostics report the actual attempts, not the number of branches. For FIML, only NULL or 3 is supported: three starts per solver, with refinements counted separately.

control

A sem_control() object, or a plain list of options passed to the optimizer (nloptr), the same as ⁠sem_control(nloptr = <list>)⁠. An n_starts given both here (in sem_control()) and as the argument must agree. FIML requires optimizer = "auto", an empty nloptr list (or the empty plain list) and n_starts NULL or 3, under its initial validated numerical protocol. The resolved protocol is recorded in fit@diagnostics$protocol.

weights

Optional numeric vector of non-negative case weights, one per row of data (NULL, the default, fits unweighted). The fit is weighted maximum likelihood on the weighted mean and covariance; the scale of the weights does not matter. Rows dropped for missing values drop their weights with them. Use with se_type = "sandwich". FIML rejects every non-NULL weight vector.

se_type

Character: "model" (default) takes the covariance of the estimates from the inverse information; "sandwich" uses the robust sandwich covariance A^{-1} B A^{-1} with casewise scores (HC0-type: it equals sandwich::vcovHC(type = "HC0") per equation and lavaan's robust standard errors with sampling.weights, and is smaller than the HC3 default of the glm route by a factor that shrinks like 1/n). Model-based standard errors are not valid under weights. In a two-level model (cluster) "sandwich" is the cluster-robust sandwich: per-cluster scores, B = \sum_j s_j s_j' with no small-sample factor (CR0), the observed information as A, projected under active linear constraints; it matches lavaan's se = "robust.huber.white" for the same two-level model.

meanstructure

Logical or NULL. TRUE (default) fits a mean structure; NULL fits one only when the model writes an intercept (y ~ 1, free or fixed); FALSE fits covariances only and errors if an intercept is written. With a mean structure every observed variable whose intercept is not written has a free one, so a model with only free intercepts has the same estimates and standard errors as the covariance-only fit. A latent variable's mean is fixed at 0. A model with a product term (y ~ x + m + x:m) always fits the mean structure (it needs the mediator intercept for the four-way decomposition), so with a product meanstructure = FALSE is an error. An explicit NULL or FALSE is kept as given for listwise fits. FIML requires TRUE.

fixed_x

TRUE (default), FALSE, or a character vector of exogenous observed variable names. The selected variables (TRUE: every exogenous observed variable, product columns included) have their mean (with a mean structure), variance and the exogenous covariances the model contains fixed at the sample moments of the estimation sample (weighted when weights are given) and removed from estimation, as lavaan does with fixed.x = TRUE. The structural estimates, their standard errors, the degrees of freedom and the chi-square do not change; the parameter count and the log likelihood do: the log likelihood (and so AIC and BIC) is conditional on the fixed variables, and glance()$fixed_x lists them. Models whose fixed_x sets or data differ cannot be compared with stats::anova(), mbco_sem(), AIC() or BIC(). A (co)variance or intercept statement on a selected variable is an error (lavaan would silently keep it free). The fixed rows stay in the parameter table (fixed_x column, no standard error) but not in coef() or vcov(). Left unset it resolves to an explicit subset: every exogenous observed variable (product and factor-dummy columns included) except those a ⁠~~⁠ or ~1 statement names, which are left free with a message of class medfit_message_fixed_x_lenient (an explicit TRUE errors there instead; an explicit FALSE is kept). glance()$fixed_x names the set the fit used.

sampling_weights

[Deprecated] Renamed weights, the name fit_mediation() uses; the old name still works with a warning.

missing

Exact missing-data method: listwise (default) or bounded Gaussian fiml (no abbreviations). FIML requires explicit fixed_x = FALSE; see the Bounded FIML section. The argument is appended to preserve existing positional calls.

cluster

Experimental. NULL (default) or a string: the name of the cluster column of data, for a two-level model written with ⁠level:⁠ blocks (level: 1 or level: within; level: 2, level: between or the cluster variable's name). Two-level only: cluster without ⁠level:⁠ blocks, and ⁠level:⁠ blocks without cluster, are errors (medfit_error_twolevel_cluster, which also covers more than two levels, fewer than two clusters and a missing or incomplete cluster column); misordered ⁠level:⁠ blocks are medfit_error_twolevel_syntax; a within variable constant in every cluster, or a cluster-level variable in a level: 1 row, is medfit_error_twolevel_varset. A model that passes the two-level checks is fitted by maximum likelihood (experimental); an inadmissible solution (a negative variance or a non-positive-definite implied covariance at either level) stops with medfit_error_twolevel_inadmissible, which keeps the fit and its outcome ledger. extract_mediation() on a native two-level fit returns a TwoLevelMediationData (⁠@source⁠ is "native"), with the warnings of the lavaan two-level adapter. glance() adds n_clusters, cluster_size_min and cluster_size_max (counted after listwise deletion); its chisq and p_value are NA with a note, because the engine fits no saturated two-level model. See the "Two-level models" section of medfit-syntax. Unset fixed_x means FALSE on this route; an explicit fixed_x = TRUE, meanstructure = FALSE, weights, missing = "fiml", information = "expected", latent variables, product terms and nonlinear constraints are refused with classed errors (⁠medfit_error_twolevel_*⁠); the one nonlinear row admitted is the equality of the within and between indirect effects (a_w*b_w == a_b*b_b, the null of twolevel_equal_indirect()). se_type = "sandwich" gives the cluster-robust sandwich (see se_type), and glance() then reports se_type. Appended last to preserve positional calls.

estimator

"ML" (the default) or "MLR". "MLR" keeps the ML estimates and, unless se_type is given, reports the sandwich standard errors; glance() then adds chisq_scaled, scaling_factor and p_value_scaled, the Yuan-Bentler scaled chi-square that lavaan reports for estimator = "MLR" (test = "yuan.bentler.mplus": the ML chi-square divided by the scaling factor, from the casewise scores of the model and of the saturated mean and covariance model). The Satorra-Bentler ("MLM") variant and the other lavaan estimators are not offered. "MLR" is defined for single-level complete-data fits with linear equality constraints; cluster, ⁠level:⁠ blocks, missing = "fiml", weights, and inequality or nonlinear constraints are refused with classed errors (⁠medfit_error_mlr_*⁠, each also of class medfit_error_mlr), and an unknown estimator with medfit_error_estimator. A product term that makes the model test invalid leaves the scaled statistic NA too. Appended last to preserve positional calls.

Value

A SEMFit object. With a product term whose factor is a regression target (x:m with m regressed on x), glance() reports the chi-square, df and p-value as NA with a note, and anova() and mbco_sem() refuse; see SEMFit-methods. diagnostics$ledger holds the versioned outcome ledger described below.

Defaults changed in 0.15.0

fixed_x is the exogenous observed variables (lavaan's fixed.x = TRUE) and meanstructure = TRUE, so a default fit matches a default lavaan::sem() fit. Against 0.14.x the parameter count, logLik(), AIC(), BIC() and the names in coef(), vcov() and tidy() change; the structural estimates and their standard errors did not change on the cases measured. Which random start a multi-start fit tries can change too (the retry seed follows the parameter names). To keep the 0.14.x results, pass ⁠fixed_x = FALSE, meanstructure = NULL⁠. The 0.14.x options(medfit.native_defaults) opt-in no longer has any effect.

Bounded FIML

Explicit missing = "fiml" fits a joint Gaussian random-X model under ignorable missingness (for example, MAR with the usual ignorability conditions). It evaluates observed components, without imputing values. It supports numeric continuous observed variables in four shapes: X -> M -> Y (three variables), the same model with one covariate Z, with two covariates Z1 and Z2, and two parallel mediators (see below). The X -> Y path is free or fixed exactly at zero, intercepts are free, and disturbances are independent except the free mediator residual covariance of the parallel form. Names and labels are arbitrary.

With covariates the regressions are M ~ X + Z and Y ~ M + X + Z (one covariate), or M ~ X + Z1 + Z2 and Y ~ M + X + Z1 + Z2 (two). Every exogenous variable needs a written path to Y, and every covariate path to M is free. The exogenous variables have a free joint covariance: write every pair (in either order) or none; a partial set is refused. Any variable may be incomplete. With no Y path fixed at zero, the first exogenous variable is the fit's treatment and extract_mediation() may name any exogenous variable as the treatment; with exactly one Y path fixed at zero, that variable is the treatment. Parameter counts are 8 or 9 (three variables), 13 or 14 (one covariate) and 19 or 20 (two covariates), without or with the direct path. Three or more covariates, a covariate on one equation only, residual covariances (other than the parallel mediator covariance), extra predictors beyond these, latent variables, products, factors, correlated disturbances, parameter ties, bounds, general constraints, defined parameters and syntax-supplied starts are not supported. The covariate fits are implemented and numerically verified against lavaan and an independent likelihood; their coverage has not been calibrated or statistically admitted. Input checks and local numerical gates do not establish global identification, a global optimum or inference coverage.

Two parallel mediators (M1 ~ X, M2 ~ X, Y ~ M1 + M2, with or without Y ~ X) are fitted in two forms. Independent residuals require the statement M1 ~~ 0*M2 (either order): an omitted statement is refused because lavaan's default would free it. A free, label-less M1 ~~ M2 fits the mediator residual covariance. A labeled, fixed nonzero, bounded, tied or otherwise constrained covariance is refused. The free-parameter count is 12 or 13 (independent residuals) and 13 or 14 (free covariance), without or with the direct path. extract_mediation() needs both mediators named and returns a FIMLParallelMediationData object with the full path covariance of a1, a2, b1, b2 and c_prime, so the sum of the indirect effects keeps every cross-path term. Extraction refusals for the parallel form have class medfit_error_fiml_extract_unsupported.

Two parallel mediators also take one covariate Z or two covariates Z1, Z2 (M1 ~ X + Z, M2 ~ X + Z, Y ~ M1 + M2 + X + Z, in either residual form). The covariate rules are those above: every exogenous variable has a free path to both mediators and a written path to Y, the exogenous covariance is free (write every pair or none), and any variable may be incomplete. With no Y path fixed at zero, extract_mediation() may name any exogenous variable as the treatment; with one fixed at zero that variable is the treatment. The free-parameter count is 18 to 20 (one covariate) and 25 to 27 (two), without or with the direct path and the free residual covariance. Three or more mediators, three or more covariates and a covariate on only some of the equations stay refused.

Two serial mediators are fitted in two forms, each with no, one or two covariates: the saturated forward graph M1 ~ X, M2 ~ M1 + X and Y ~ M1 + M2 + X, and the pure chain M1 ~ X, M2 ~ M1 and Y ~ M2 (the direct path Y ~ X is free, 0*X, or omitted in both without a covariate), with the independence of all three disturbance pairs written as M1 ~~ 0*M2, M1 ~~ 0*Y and M2 ~~ 0*Y (either order within a pair; an omitted or free statement is refused). The saturated model has 14 free parameters (13 with the direct path fixed) and is just identified with the direct path free, so a pair of variables that is never observed together makes the fit fail closed (medfit_sem_fiml_error at the numerical stage). The chain has 12 free parameters (11 with the direct path fixed), is overidentified (2 or 3 degrees of freedom) and so is a restriction the data can reject; it fails closed for fewer unobserved pairs. A graph with exactly one of the two shortcuts, and a fixed or labeled shortcut, is refused. With one covariate Z it predicts M1, M2 and Y (M1 ~ X + Z, M2 ~ M1 + X + Z or M2 ~ M1 + Z, Y ~ ... + X + Z), X and Z have a free covariance, and every exogenous variable needs a written Y path (free; at most one fixed at exactly zero, which makes that variable the treatment). The saturated model then has 20 free parameters (19) and the chain 18 (17). With two covariates Z1 and Z2 both predict every equation, the three exogenous covariances (X ~~ Z1, X ~~ Z2, Z1 ~~ Z2) are all written or none (a partial set is refused), and the saturated model has 27 free parameters (26) and the chain 25 (24). In the pure chain the treatment is structural, the variable with no path to M2: leaving a variable out of the equation of M2 makes it the treatment, and exactly one variable may be left out. In the saturated graph with a fixed-zero direct path the variable with the fixed-zero path is the only valid treatment. extract_mediation() needs both mediators named in the fitted order (the reversed order is refused) and returns a FIMLSerialMediationData object with the full covariance of a, a2 (X to M2), d1 (M1 to M2), b1 (M1 to Y), b and c_prime; nie() is the chain effect a * d1 * b, nie(type = "total") adds a2 * b + a * b1, and paths(), tidy(), coef(type = "paths") and summary() list all six paths. For the chain the object has the four paths a, d1, b and c_prime, and nie() and nie(type = "total") are the same effect. The covariate's coefficients are never paths: the aliases are the treatment's. In the saturated graph with a free direct path a covariate may be named the treatment; in the pure chain naming a covariate is refused (both covariates, with the classed medfit_error_fiml_extract_unsupported). Its normal intervals are available; pm(), quick(), glance() and bootstrap intervals are not (bootstrap_mediation(source_fit = ) stays withheld, and behind that guard a serial fit raises medfit_error_fiml_serial_source_fit). Serial models with three or more covariates and every other serial shape stay refused.

Supply fixed_x = FALSE explicitly; omission, TRUE and named subsets are errors. Require meanstructure = TRUE, information = "observed", se_type = "model", no weights, empty control, and n_starts = NULL or 3. These numerical-control restrictions reproduce the initial validated protocol. Missing values never select FIML automatically, and a failed fit never falls back to listwise deletion. fit_mediation() with engine = "sem" forwards these settings through engine_args; its se_type = "model" remains a top-level argument.

nobs() counts rows with any observed model variable; n_dropped counts only all-empty rows. Singleton patterns and data with no complete rows are supported when the local identification and information checks pass. Original positional row IDs and pattern counts are retained. logLik() includes the full Gaussian constants, with its df attribute equal to the free-parameter count (8 or 9 for three variables; see above for covariates). AIC and BIC use that likelihood and retained row count. The discrepancy f and model-test df are NA: no saturated missing-data reference model is fitted.

Supported operations include SEMFit coefficient/covariance and likelihood summaries, parameter tidy/normal confidence intervals, and extraction followed by paths(), nie(), nde(), te(), coef(), vcov(), print/summary, tidy and normal path/effect confidence intervals. Extracted aliases follow topology; source labels/full covariance remain in the validated durable fit context. At a = b = 0, the NIE point value remains available but its inferential fields are unavailable; a known fixed direct path is a different case.

SEMFit glance() reports likelihood/IC fields with unavailable model-test fields; extracted-object glance(), quick(), pm(), extracted-object bootstrap, profiles, MBCO and fit tests remain unavailable. The bootstrap_mediation() source_fit intervals are implemented but withheld (refused with a classed error) until statistical admission is decided; a covariate fit is additionally refused with medfit_error_fiml_covariate_source_fit (including a parallel fit with covariates) and a parallel fit without covariates with medfit_error_fiml_parallel_source_fit, so no source-fit interval exists for either. Delta-method Wald intervals stay available for these extracted objects; as for the three-variable model, the NIE standard error is NA only at the exact origin (every a and b path exactly zero). Object-aware package guards precede package-controlled refits/RNG/workers; opaque user callbacks and external-first dispatch remain outside that guarantee. Adapter/topology/numerical failures retain stage, reason, original parent and completed attempts; basic argument-type errors can occur earlier. A dedicated fiml-1 ledger binds likelihood, rows, settings and attempts; the version-1 ledger below continues to describe listwise fits. See the Methods and Formulas article, Bounded FIML, for the likelihood and the sem engine guide for the supported workflow. Bounded FIML was introduced in 0.16.0; released 0.15.0 does not provide this option.

Nonzero-product search coverage

One equality c*a*b == q is supported when the constants and q/c are finite and nonzero, a and b are distinct free scalar labels after expanding definitions, and no other constraint row involves either label. The engine fits both signs of a independently with the existing optimizer and acceptance gates, respecting user bounds and effective variance floors. It returns the lowest accepted discrepancy only when each required sign branch is accepted or excluded by an explicit bounds contradiction. An unresolved branch stops the fit with medfit_error_no_convergence; an all-empty search returns no fit. Zero-product fitting is unchanged. Repeated factors, multiple product equalities, coupled rows and other unsupported shapes retain local search.

internals$search_evidence is a separate versioned internal record, not a change to the outcome-ledger schema. Its coverage is charted for covered sign branches, local for unsupported shapes, or unresolved for an incomplete search. It retains restrictions, context, branch states, candidates, objectives, gates and attempts; validation checks their attribution to the model and sample. Charted coverage does not prove a global optimum within a branch. Existing optimum status meanings are retained, and objects without this optional record remain usable. Counts distinguish optimizer starts, accepted starts and synthetic reference attempts.

The stored raw constraint residual is diagnostic only. Its optional standardized value uses the gradient and covariance at an already available matching reference fit without the tested restriction, never the projected constrained covariance. No additional fit or covariance calculation is requested. The ordinary optimizer reference lacks covariance, so the standard error and standardized residual are NA with reason reference_covariance_unavailable. These diagnostics do not affect acceptance or inference.

Constrained standard errors

Observed-information covariance includes the curvature of active nonlinear constraints; expected information retains its Fisher definition. Sandwich standard errors use the corresponding information as bread. Active inequalities, user bounds and solver variance floors give a local tangent covariance, with exactly zero variance for a pinned coordinate. This is not the full sampling distribution at a boundary. See the Methods and Formulas article, under Constraints, for the covariance formula.

Outcome ledger

diagnostics$ledger is a list with schema_version = 1L. Each node has id, parent_id, the exact parsed constraints, and context (the estimation sample, the model syntax and parameters, the likelihood domain, the settings and n_obs). enumeration records state and the number of required children; complete means every required restriction was attempted, not that any was globally optimized. outcome is resolved or unresolved. Separate fields record optimizer (acceptance state, original status, decrement, retries and optimum diagnostics), likelihood (availability and f), feasibility (witness or unknown), covariance (available, unavailable, not_retained or failed), improper, the retained notices (warnings and messages), the original condition (class, message, call) and the recursive children. IDs are deterministic positions within the call, not certificates of equivalent parameter spaces. No global optimum is asserted, and a failed branch is unknown, never certified infeasible.

A node whose constraints hold zero-product rows also has branch_map: state, raw_count, the parser factor_counts, unique_count and raw_to_canonical, a structural restriction-set ID for each raw row. The IDs collapse duplicate or permuted constraint rows, not arbitrary affine equivalence, and every raw row is still fitted in its original order (ties go to the first). More than 64 raw combinations, duplicates included, is refused before the grid is allocated, even when the unique count would be smaller; that node is not_enumerated, with an unknown unique count and no raw mapping, and nothing is fitted or certified. Its message prints the count without scientific notation, labels a count above 2^{53} as approximate (a double need not be an exact cardinality there) and names an overflow; raw_count is Inf on overflow. If the map cannot be built while an error is recorded, its state is unavailable with that condition, and the original error is not replaced. The map is rebuilt from the node's constraints during validation, so a forged map is refused.

The one proof of emptiness in this version-1 ledger is the literal certificate literal_zero_nonzero: an explicit label == 0 equality and an explicit finite nonzero literal equality on the same parsed label (a == 0 with a == 1). Its label, source rows and values are kept in certificate and rebuilt from the node's own parsed parameters and constraints before any inference uses it. A certified-empty branch is retained with outcome = "excluded", feasibility = "certified_empty" and an unavailable likelihood: it is not fitted and is not a successful fit. No tolerance, solver status, numerical rank, bound, general affine contradiction or fixed value in the parameter table is a proof, and a literal too small to represent (1e-999) is unknown.

A zero-product fit returns only if at least one required branch resolves and every other branch resolves or is certified empty. A direct fit whose own equalities contradict literally stops with medfit_sem_infeasible, and a union whose every branch is certified empty with medfit_sem_empty_union; both are refinements of medfit_error_no_convergence and carry the ledger. Otherwise it stops with a medfit_error_no_convergence error, never a fit; the error carries the ledger of every required branch as ⁠$ledger⁠ and, when a branch survived, ⁠$best_survivor⁠ (its id and discrepancy f, diagnostic only, never a p-value). The union's own node does not aggregate its children's notices; inspect each child. The notices of a failed call are in the ledger only; the error message keeps its text. A data or model error keeps its own class and also carries ⁠$ledger⁠. The estimation sample is stored once, on the root node; a descendant fitted on the same rows carries only context$sample_hash. A fit made before the ledger existed must be refitted before mbco_sem() can use it, which refuses it with a medfit_error_ledger error.

When the optimizer accepts a fit and the covariance stage explicitly diagnoses non-positive-definite information or a negative variance, the call stops with medfit_sem_covariance_error, never a fit. The class is a sibling of medfit_error_no_convergence: no optimizer failed, so the handlers that report an unresolved result for an optimizer failure do not take it. Its fields are schema_version = 1L, stage = "covariance", partial (the accepted optimizer result: f, theta, sample, domain, dimensions and settings; no vcov or defined) and ledger (the same node as partial$ledger, with covariance = "failed" and post_fit: versioned evidence with the original condition's class, message, call and diagnostic kind, information_not_pd or negative_variance). Other covariance errors propagate unchanged, without a retained likelihood. Singular information still warns and returns an NA covariance, recorded as unavailable rather than failed. The message is the original one. Resolved here means an accounted-for accepted likelihood, not a successful covariance. A union root reports the first failing branch's post_fit, in branch order, even when another branch supplies its minimum likelihood, and does not claim the winning branch failed: inspect the branch IDs. A branch that did not converge still stops the call with medfit_error_no_convergence first. Definition values and gradients are checked before the covariance, and model, data, optimizer, objective and other errors get no covariance certificate. The condition is not accepted as an input to mbco_sem(), and a fit that carries post_fit is refused with medfit_error_ledger.

See Also

SEMFit, fit_mediation()

Examples


fit <- fit_sem(
  "mediator1 ~ a*treatment\noutcome ~ b*mediator1 + treatment\nab := a*b",
  data = mediation_demo, fixed_x = FALSE, meanstructure = NULL
)
fit@defined

# A treatment-by-mediator product: the four-way decomposition
fit4 <- fit_sem(
  "mediator1 ~ treatment\noutcome_int ~ treatment + mediator1 + treatment:mediator1",
  data = mediation_demo, se_type = "sandwich"
)
decompose(extract_mediation(fit4, treatment = "treatment", mediator = "mediator1",
                            outcome = "outcome_int"))



Joint Effects at a Given Parameter Vector

Description

Recomputes the joint CDE, NDE, NIE and total effect of a JointMediationData object from a named parameter vector, holding the object's structure, reference levels (m_star) and sample covariate means fixed. With the default estimates = object@estimates it returns the stored effects. Its main use is as the statistic of a parametric bootstrap: the draws bootstrap_mediation() passes to statistic_fn are named like ⁠@estimates⁠, and the NDE needs the prefixed intercept and covariate rows (m1_, ..., y_) and the covariate means, not only the path aliases.

Usage

joint_effects(object, estimates = object@estimates)

Arguments

object

A JointMediationData object.

estimates

Named numeric vector containing every prefixed source row of object@estimates (m1_..., y_...); alias rows are ignored. A missing source row is an error, not a zero.

Value

Named numeric vector: cde, nde, nie, te.

Examples

d <- mediation_demo
fit <- extract_mediation(
  lm(mediator1 ~ treatment + covariate1 + covariate2, d),
  model_y = lm(outcome_int ~ treatment * mediator1 + mediator2 +
                 covariate1 + covariate2, d),
  treatment = "treatment", mediator = c("mediator1", "mediator2"),
  mediator_models = list(lm(mediator2 ~ treatment + mediator1 +
                              covariate1 + covariate2, d))
)
joint_effects(fit)

# Parametric bootstrap of the joint NIE
boot <- bootstrap_mediation(
  function(theta) joint_effects(fit, theta)[["nie"]],
  method = "parametric", mediation_data = fit, n_boot = 500, seed = 1
)
boot@ci_lower
boot@ci_upper

Minimum-of-k Likelihood-Ratio Test for an Indirect Effect (MBCO)

Description

Tests the null hypothesis that an indirect effect, the product of two or more labeled paths (a b, or a serial a d b), is zero in a model fitted by fit_sem(). The product is zero exactly when one factor is, so the model is refitted once per path with that path set to zero; each is a linear equality constraint, so each refit is a single solve. The statistic is the smallest of the likelihood-ratio statistics, referred to a chi-square distribution with one degree of freedom (the minimum-of-k LRTs; see the Methods and Formulas article). The nonlinear constraint a b = 0 is never solved, because a nonlinear solver can stop at the branch with the larger statistic.

Usage

mbco_sem(
  object,
  a,
  b,
  n_starts = NULL,
  control = NULL,
  fit = lifecycle::deprecated(),
  paths = NULL
)

Arguments

object

A SEMFit from fit_sem(), fitted without weights.

a, b

Character strings: the labels of the two free regression paths whose product is the indirect effect (for example "a" and "b" in "M ~ a*X" and "Y ~ b*M"). They must be different, and each must be a labeled ~ row of the fit; a variance, a loading, an unlabeled path and a defined parameter are refused. For a product of more than two paths pass them all as paths, or as a character vector in a with b missing.

n_starts, control

Passed to the optimizer for the two refits, as in fit_sem(): control is a sem_control() object or a plain nloptr list. NULL, the default, uses the settings object was made with, so a better optimum in the full fit than in a refit cannot inflate the statistic; an explicit value overrides them (an explicit sem_control() replaces the stored nloptr options, as an explicit list does).

fit

[Deprecated] Renamed object; the old name still works with a warning.

paths

Character vector of two or more labels: the paths whose product is the indirect effect (c("a", "d", "b")). NULL, the default, uses a and b.

Details

Bounded FIML fits are refused before any constrained refit; their model tests and MBCO inference are not supported. See fit_sem() for the bounded limits.

A fit made with weights is refused: the weighted discrepancy is not a likelihood, so its difference is not chi-square. So is a fit that did not converge, since its discrepancy is the reference both refits are measured against.

A fit whose ledger is missing, malformed or does not describe the fit, and a refit that is not the null asked for, are refused with a medfit_error_ledger error: the evidence is never inferred from converged.

A refit that fails the acceptance gate of the optimizer does not stop the function: its row has converged = FALSE, f and diff_ll NA and the failure text in note, a warning repeats the text, and statistic and p.value are NA (never the minimum over the refits that worked, which would hide the failure). A zero-product branch that cannot be fitted stops fit_sem() itself (there is no partial fit to test against).

Inequality constraints in the model matter only when they put the null on the boundary of the parameter space. If a bound or an inequality that involves the tested parameter is active at its refit (a > 0 with the null a = 0), the function warns that the statistic is a mixture of chi-squares, not chi-square(1), and that the p-value is not valid. A bound the null sits inside (a < 0.2), an inactive inequality and one on another parameter are not mentioned. A null the constraints rule out (a > 0.3 with the null a = 0) is an unresolved row whose note says so.

Only a product of labeled paths is tested; a sum of products (several parallel indirect effects together) is not. If two of the paths are tied by an equality (a == b), their refits impose the same restriction and their diff_ll values coincide. The test is conservative: under a null where only one factor is zero its size is at most the nominal level, and with more than one zero factor it is smaller still.

A native two-level fit (experimental) is tested at one level: mbco_sem(fit, "a_w", "b_w") for the within indirect effect and mbco_sem(fit, "a_b", "b_b") for the between one, with each null refit on both levels and the same clusters. The statistic is the minimum likelihood ratio over the refits with one path set to 0, referred to chi-square(1); it is conservative at the origin (both paths zero) and is not a test of the between-minus-within contrast. Paths from different levels, or a label shared by both levels, are refused with class medfit_error_twolevel_unsupported. A null refit whose solution is inadmissible (a negative level-2 variance) gives the unresolved result above (statistic NA) with a warning of class medfit_warning_twolevel_inadmissible that names the refit and the reason; one that does not converge gives the same result with a warning. The statistic is never the other null's likelihood ratio alone. A warning says when a level-2 variance at a refit is below 1% of that variable's implied between plus within variance, because the null then lies near the boundary and chi-square(1) may not hold.

Value

An object of class c("mbco_sem", "htest"): statistic (the smallest diffLL), parameter (df = 1), p.value, method, data.name, n_obs, unresolved (TRUE when any refit failed, see Details), and tests, a data frame with one row per refit (constraint, the minimized discrepancy f, diff_ll equal to n_obs * (f - fit@f), converged, and note, the failure text of a refit that could not be fitted, otherwise empty). It prints with the standard htest layout. ledger is the version-1 outcome ledger documented in fit_sem(), with children mbco/full and mbco/null:1, mbco/null:2, ..., in the requested path order. A null refit that is itself a zero-product union keeps its branch children and notices. A null node's notices also record those raised at the MBCO boundary, including the union winner's replay, so they can repeat a child's. Every null is attempted even if another fails, and an unresolved null leaves the root unresolved. A nested union branch that is certified empty by a literal zero/nonzero contradiction (see the outcome ledger in fit_sem()) is retained as excluded; a null that is itself infeasible or an all-empty union stays an unresolved row, never a finite LR or a survivor-only p-value. A null whose optimizer accepted but whose covariance stage explicitly diagnosed non-positive-definite information or a negative variance (medfit_sem_covariance_error in fit_sem()) keeps its likelihood after a check that it is the null asked for (same rows, domain and one more restriction): the row stays resolved, the statistic and p-value are unchanged, a warning names the failure, and the node has covariance = "failed" with post_fit and the notices. No covariance is invented; a fit that carries post_fit is refused as object. Other covariance errors propagate unchanged; singular information keeps its warning and NA covariance. For a native two-level fit (fit_sem(cluster = )) the result adds level ("within" or "between") and n_clusters; a single-level result does not have them.

See Also

fit_sem(), SEMFit

Examples


fit <- fit_sem(
  "mediator1 ~ a*treatment\noutcome ~ b*mediator1 + treatment",
  data = mediation_demo, fixed_x = FALSE, meanstructure = NULL
)
mbco_sem(fit, "a", "b")

# a serial indirect effect, the product of three paths
serial <- fit_sem(
  paste0("mediator1 ~ a*treatment\nmediator2 ~ d*mediator1 + treatment\n",
         "outcome ~ b*mediator2 + treatment"),
  data = mediation_demo
)
mbco_sem(serial, paths = c("a", "d", "b"))



Simple Mediation Analysis

Description

A simplified entry point for mediation analysis. Specify the data and variable names, and get results with minimal configuration.

This is the recommended starting point for most mediation analyses. For more control over model specifications, use fit_mediation() directly.

Usage

med(
  data,
  treatment,
  mediator,
  outcome,
  covariates = NULL,
  boot = FALSE,
  n_boot = 1000L,
  seed = NULL,
  ...
)

Arguments

data

A data frame containing all variables

treatment

Character: name of treatment (exposure) variable

mediator

Character: name of mediator variable

outcome

Character: name of outcome variable

covariates

Character vector: names of covariates to include (optional, default: none)

boot

Logical: compute a bootstrap confidence interval for the indirect effect? (default: FALSE for speed). Uses a parametric bootstrap of a b with a 95% percentile interval, attached to the result as the "bootstrap" attribute; call bootstrap_mediation() directly for another method or level.

n_boot

Integer: number of bootstrap samples (default: 1000)

seed

Integer: random seed for reproducibility (optional)

...

Additional arguments passed to fit_mediation()

Details

med() is designed to be the simplest way to run a mediation analysis. It constructs the model formulas automatically from variable names.

Default Behavior

Accessing Results

After running med(), use:

Value

A MediationData object with mediation results

See Also

fit_mediation() for full control, quick() for instant summary, nie(), nde(), te(), pm() for extracting effects

Examples

# mediation_demo is simulated data bundled with medfit; its covariates
# confound the mediator-outcome relation, so adjust for them
result <- med(
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1",
  outcome = "outcome",
  covariates = c("covariate1", "covariate2")
)
print(result)

# Quick summary
quick(result)


# With bootstrap CI (slower)
result_boot <- med(
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1",
  outcome = "outcome",
  covariates = c("covariate1", "covariate2"),
  boot = TRUE,
  n_boot = 1000,
  seed = 42
)



medfit Model Syntax

Description

The model syntax read by fit_sem() and by fit_mediation(engine = "sem") (the sem engine; "native" is the legacy spelling). It is a lavaan-style core plus two extensions, each marked "medfit extension" below. One statement per line (or separated by ⁠;⁠).

Missing-data scope

The general syntax below describes the default listwise path. The separate bounded fit_sem(missing = "fiml", fixed_x = FALSE) option accepts only three numeric observed variables in simple mediation with a free or exactly zero direct path and free intercepts. General constraints, definitions, starts, bounds, latent variables, products and factors are not supported for FIML. See fit_sem() for all settings and downstream limits.

Core statements

Statement Meaning
y ~ x1 + x2 regression of y on x1 and x2
f =~ y1 + y2 + y3 latent variable f measured by the indicators
y1 ~~ y2 covariance; y1 ~~ y1 a variance
y ~ x + m + x:m product term: the observed variable x * m as a regressor (see Product terms)
y ~ a*x label the path a; equal labels are one parameter
y ~ 0.5*x fix the path at 0.5
y ~ start(0.3)*x, ⁠lower(0)*⁠, ⁠upper(1)*⁠ starting value, lower and upper bound
a == b, a + b == 1, cp == a*b equality constraint on labels; may be nonlinear
a < b, a > 0 inequality constraint; label < number is a bound
ab := a*b defined parameter, with a delta-method standard error

Constraints may be nonlinear in the labels (cp == a*b, a*b == 0.1, a*b > 0.1, ab > 0 with ab := a*b), solved with the Jacobian recomputed at every point; a model with one tries every start and keeps the best accepted solution, warning when the starts disagree. For such a model the residual variances that appear in a nonlinear row get a lower bound of 1e-4 times their natural unit (the variable's variance), because a step to a negative variance is outside the row's domain; the fit warns when a bound is active, and a residual variance below that bound (an R-squared above 0.9999) is not fitted exactly. The model without the nonlinear rows is fitted first: its estimate, and copies of it with the signs of the regression paths in the rows flipped (a product constraint cannot change sign along its surface, so each sign pattern is its own branch), are extra starts, and a feasible reference estimate is never replaced by a worse accepted fit. Models without a nonlinear row are not affected. One nonzero-product equality (a*b == 0.1, including a finite nonzero constant multiplier and definition aliases) has a separate search for each sign of its two distinct free labels. Each required sign branch must be accepted or excluded by its bounds; an unresolved branch stops the fit. Multiple product equalities, repeated factors and another constraint involving either factor retain local search. The internal coverage record distinguishes charted branches from local search, not global from local optima; see fit_sem(). A product of labels set to zero (a*b == 0, b1*b2*b3 == 0) is instead solved exactly: one linear fit per factor (a == 0, b == 0), keeping the smallest discrepancy; if a branch cannot be fitted, fit_sem() stops with a medfit_error_no_convergence error instead of returning the best of the others; the error carries the outcome ledger of every branch as ⁠$ledger⁠ (see fit_sem()). A sum of products (a1*b1 + a2*b2 == 0) has no exact reduction, so it is best-effort: the fit is the best of the starts tried, a disagreement warning means a better optimum may exist, and n_starts raises the number of starts. Constrained standard errors use the active tangent space: observed information includes nonlinear constraint curvature, while expected information retains its Fisher definition. Active inequalities and bounds, including solver variance floors, give a local tangent approximation rather than the full boundary sampling distribution. See fit_sem() and the Methods and Formulas article for details. Labels used in a constraint or a definition must be defined in the model. A constraint with no free parameter is an error. Exogenous variables are given free variances and covariances, as lavaan does with fixed.x = FALSE. An exogenous variable named in any ⁠~~⁠ statement is left out of that pairing: its variance and the covariances the model writes are kept, and its covariances with the other exogenous variables are 0 unless written (lavaan does the same). fixed_x = TRUE (or a vector of names) in fit_sem() fixes the moments of the selected ones at the sample values instead, as fixed.x = TRUE does. Unlike lavaan, which keeps an explicit x ~~ x or x ~ 1 free under fixed.x = TRUE and lets the degrees of freedom move, medfit stops with an error when the model has a statement on a selected variable's moments. Any intercept statement (y ~ 1, or 1 as a term: y ~ 1 + x) turns the mean structure on and frees every observed intercept the model does not write, as lavaan does; y ~ 0*1 then restricts the mean of y to 0 (one degree of freedom), and meanstructure = TRUE in fit_sem() turns it on without any statement, and a product term (x:m, see Product terms) always turns it on. A latent variable's mean is fixed at 0; a free latent ~1 is an error. A repeated 1 for one variable is an error. A variable cannot appear on both sides of ~ or ⁠=~⁠ (y ~ y), and a path, a (co)variance or an intercept takes one row: a repeated y ~ x is an error, not a second row that competes for the label.

Factor covariates

A factor, character or logical column named on a regression's right side is replaced by one 0/1 dummy per non-reference level, named ⁠<column>_<level>⁠ (g with levels a, b, c gives g_b and g_c). The reference level is the first factor level; a character column sorts in the C locale, so the result does not depend on the session locale. A logical column gives one dummy, ⁠<column>_TRUE⁠. Dummies are built from the full column before rows with missing values are dropped, and a missing value in the factor drops the row once. tidy() and the parameter table show the dummies by name, and the fit's data holds the dummies, not the factor.

Limit Message (starts with, or contains)
An ordered factor "is an ordered factor"
A factor with one level "has only one level"
A level that makes an invalid name "makes the invalid name"
A dummy that is already a column "is already a column of data"
A label, fixed value, start or bound on a factor (b*g) "expands to"
A constraint that names the factor (g == 0) "is a categorical column"
A product of two factors "both sides are categorical columns"
A dummy with no variation in the rows used "is constant in the rows the fit uses"
A factor as the outcome or a mediator "must be numeric"
A factor as treatment or mediator in extract_mediation() "is a factor in the model"

A label goes on one dummy: b*g_b works, b*g stops, and a constraint names the label (b == 0), never the factor. A bootstrap that refits from raw data re-expands the factor in each resample, so a level missing from a character column's resample changes the reference level. g:m expands to g_b:m and g_c:m, each a product term under the rules below. fixed_x = "g" fixes every dummy of g, and a dummy name fixes one. A factor covariate in the mediator equation enters the four-way covariate means through its dummies; a factor treatment or mediator is not supported (recode a two-level factor as a 0/1 numeric column), and the four-way route refuses a g:m product because its effects differ by level.

Product terms

x:m is the product of two observed variables, written with no spaces, on the right side of a regression (y ~ x + m + x:m). As in lavaan, the product is an observed exogenous variable: the engine builds the column x * m from data after listwise deletion, with a free variance, free covariances with the other exogenous variables and (the mean structure is on) a free mean. The likelihood does not change. x:m and m:x are one term, stored and printed under the canonical name, the two names sorted in the C locale (m:x); the coefficient is named y~m:x, or by its label (b*x:m labels the whole product). extract_mediation() finds the treatment-by-mediator product through the same name and returns the four-way decomposition; centering the mediator moves the split between the controlled direct effect and the reference interaction, not the natural effects.

A column in data named m:x or x:m is used only if it equals x * m on the rows kept; otherwise the fit stops. A product term turns the mean structure on, and meanstructure = FALSE is then an error. A coefficient equals the equation-wise least-squares estimate inside the class below, and the sandwich covariance (se_type = "sandwich") is the standard-error choice, because a product is not normal; the engine warns once when it is not used. fixed_x includes the product columns.

Limit Message (starts with, or contains)
A space around : "a product ':' needs a variable name on each side, written without spaces (x:m)"
x:x "of a variable with itself is not supported"
x:m:w "a three-way or higher product"
Product as a left side (x:m ~ y, x:m ~~ y) "cannot be a left side"
Product in ⁠=~⁠ "is only valid on the right side of a regression"
Product inside a constraint or ⁠:=⁠ "not inside the expression"
A latent variable in a product "products with latent variables are not supported in this version"
y ~ x:m + m:x (one product twice in an equation) "are the same product (canonical name"
A factor that is the target or downstream of it (y ~ x + x:y) "(rule 8: no outcome-derived regressors)"
A loop of regressions "The model is not recursive"
A residual covariance between outcomes (m1 ~~ m2) "cannot have a residual covariance (rule 9)"
A label shared by two rows "is used on more than one parameter"
A fixed coefficient (0.3*x, 0*x) "has a fixed coefficient (rule 9)"
A bound (lower(0)*x) "has a bound (rule 9"
==, < or > naming a coefficient label "names the coefficient label"
A fixed, shared or constrained intercept "(rule 9, intercept clause"
meanstructure = FALSE with a product "meanstructure = FALSE, but the model has a product term"
A column m:x in data that is not x * m "is not the product of"
A product input that is not numeric, factor, character or logical (a date) "needs numeric variables"
information = "expected", endogenous factor "with a product of an endogenous variable"
anova() or mbco_sem() on such a fit "is not available for ... a model with a product term"
Another product on the treatment or mediator, in extract_mediation() "does not support the product"
AIC() or BIC() on fits with different observed variables "different observed variables"
A product of two categorical columns (g:h) "both sides are categorical columns"
fixed_x naming a column that appears only inside products "appears only inside products"
A product in a modifier (y ~ a:b*x) "malformed modifier"
Four-way on a native fit without the treatment-by-mediator product "needs the treatment-by-mediator product"
extract_mediation(interaction = ) that is not a : product "must be the product written with :"
extract_mediation(interaction = ) that is not treatment by mediator "is not the product of the treatment"

Each error has one of these classes and also the class medfit_error_product; the message is the reason, so a handler can match the class and a reader the message. The warning that the model test is not valid (below) has the class medfit_warning_product_modeltest.

Class Raised for
medfit_error_product_syntax spacing, x:x, three-way, left side, ⁠=~⁠, constraint expression
medfit_error_product_latent a latent variable in a product
medfit_error_product_duplicate one product twice in an equation
medfit_error_product_outcome_regressor rule 8
medfit_error_product_recursive a loop of regressions
medfit_error_product_residual_covariance residual covariance between outcomes
medfit_error_product_shared_label a label on two rows
medfit_error_product_fixed_coefficient a fixed coefficient
medfit_error_product_bound an inline bound
medfit_error_product_constraint a constraint names a coefficient label
medfit_error_product_intercept a fixed, shared or constrained intercept
medfit_error_product_meanstructure meanstructure = FALSE
medfit_error_product_column a data column that is not the product
medfit_error_product_nonnumeric a non-numeric product input
medfit_error_product_information information = "expected", endogenous factor
medfit_error_product_modeltest anova() or mbco_sem()
medfit_error_product_observed AIC() or BIC() across observed variables
medfit_error_product_extract extract_mediation() refusals

Rules 8 and 9 are checked on the parsed table, so they need no data. Rule 8 rejects a regressor built from the outcome (it is correlated with the equation's error); rule 9 names what is not yet supported with products, and the same model works without the product. The covariance that completion would add between two pure outcomes is fixed at 0 in a product model, with one note. Products of observed variables only: a product with a latent variable, x:x and three-way products are not supported.

The global chi-square is not valid when a factor of a product is itself a regression target (the model treats the product as exogenous although it is a function of that variable) or when the exogenous (co)variance block is restricted. glance() then reports chi-square, df and p-value as NA with a note, anova() and mbco_sem() refuse, and expected information is refused for an endogenous product; logLik(), AIC and BIC stay defined, but those of a fit with a product are not comparable with those of a fit without one, so AIC(fit_a, fit_b), BIC(), anova() and mbco_sem() refuse such a pair. A product of exogenous variables with the block free keeps the ordinary test.

Two-level models (experimental)

A two-level model of observed variables is written in ⁠level:⁠ blocks and fitted with fit_sem(model, data, cluster = "<cluster column>"). level: 1 and level: within open the within block; level: 2, level: between and ⁠level: <cluster column>⁠ (as lavaan writes it) open the between block. Every row belongs to a block, each level appears once, and level 1 comes first. A variable named in level: 1 rows (a within variable) must also appear in level: 2 rows and must vary within clusters; a variable named only in level: 2 rows is a cluster-level variable and must be constant within each cluster. The same label at both levels is an equality constraint across levels. Paths have fixed slopes (no random slopes), and the between part of each within variable is a latent cluster mean. Level-2 variances are fitted without a floor: an inadmissible solution (a negative variance or a non-positive-definite implied covariance at either level) is the error medfit_error_twolevel_inadmissible, which carries the fit (fit) and its outcome ledger (ledger). Unset fixed_x means FALSE and unset meanstructure means TRUE on this route.

Limit Message (starts with, or contains)
⁠cluster =⁠ without ⁠level:⁠ blocks "is given but the model has no ⁠level:⁠ blocks"
⁠level:⁠ blocks without ⁠cluster =⁠ "the model uses ⁠level:⁠ blocks but cluster is not given"
A cluster column that is not in data "is not a column of data"
Missing values in the cluster column "has missing values; drop those rows first"
Fewer than two clusters "has fewer than 2 clusters"
More than two levels "the model has more than two levels"
An unknown level name (level: school with another cluster column) "malformed level line"
A row before the first ⁠level:⁠ line "has statements before the first ⁠level:⁠ line"
A level written twice "appears more than once"
level: 2 without level: 1 "rows but no level: 1 block"
A variable named only in level: 1 rows "every level-1 variable also needs a level: 2 row"
A within variable constant within every cluster "a cluster-level variable belongs only in level: 2 rows"
A level: 2-only variable that varies within a cluster "must be constant within each cluster"
Latent variables (⁠=~⁠) "latent variables (⁠=~⁠) are not supported in a two-level model"
A product term (x:m) "a product term (x:m) is not supported in a two-level model"
weights "weights are not supported in a two-level model"
missing = "fiml" "missing = ... incomplete rows are dropped (listwise)"
Nonlinear constraints (not a_w*b_w == a_b*b_b) "nonlinear constraints (including a product of labels"
An explicit fixed_x = TRUE or a name vector "a two-level model takes fixed_x = FALSE only"
meanstructure = FALSE "meanstructure = FALSE is refused"
information = "expected" "information = ... is not supported in a two-level model; use"
An inadmissible solution "the two-level solution is inadmissible"
compare_lr() on the fit "is not available for a native two-level fit yet"
mbco_sem() with paths from different levels "tests a product of paths at one level of a two-level fit"

mbco_sem(fit, "a_w", "b_w") and mbco_sem(fit, "a_b", "b_b") test the indirect effect at one level: the minimum likelihood ratio over the refits with each labeled path set to 0, referred to chi-square(1), as for a single-level fit. The test is conservative when both paths are zero, and it is not a test of the between-minus-within contrast. The result adds level and n_clusters; see mbco_sem().

extract_mediation() on the fit returns a TwoLevelMediationData, the same class as the lavaan two-level adapter gives, with ⁠@source⁠ "native". glance() reports df, the total log likelihood, nobs, n_clusters and the cluster-size range; chisq and p_value are NA with a note, because the engine fits no saturated two-level model. The model page "Two-level mediation (1-1-1)" has a worked example.

Defaults changed in 0.15.0

Since medfit 0.15.0 an unset fixed_x means the exogenous observed variables (as lavaan's fixed.x = TRUE) and an unset meanstructure means TRUE, so every observed intercept is free without a ~1 statement. Against 0.14.x the parameter count, logLik(), AIC(), BIC() and the parameter names move; the structural estimates and their standard errors did not move on the cases measured. A variable a ⁠~~⁠ or ~1 statement names is left free (message class medfit_message_fixed_x_lenient) instead of the error an explicit fixed_x = TRUE gives. To keep the 0.14.x results, pass ⁠fixed_x = FALSE, meanstructure = NULL⁠. The 0.14.x options(medfit.native_defaults) opt-in no longer has any effect. fit_sem() has the details.

medfit extensions

Expressions

Both sides of a constraint and the right side of a definition are arithmetic expressions in the labels, with ⁠+ - * / ^⁠, parentheses, finite numbers, and the functions exp, log, log10, sqrt, abs, min, max, sin, cos, tan, pnorm and qnorm. Anything else is rejected with the construct named.

See Also

fit_sem(), SEMFit

Examples


# Labeled paths and a defined parameter
fit_sem(
  "mediator1 ~ a*treatment\noutcome ~ b*mediator1 + cp*treatment\nab := a*b",
  data = mediation_demo, fixed_x = FALSE, meanstructure = NULL
)@defined

# Comma shorthand: one left-hand side per name
coef(fit_sem(
  "mediator1, mediator2 ~ treatment\noutcome ~ mediator1 + mediator2 + treatment",
  data = mediation_demo
))[1:3]

# An equality constraint, written with the CONSTRAINT() keyword
coef(fit_sem(
  "mediator1 ~ a*treatment\noutcome ~ b*mediator1 + treatment\nCONSTRAINT(a == b)",
  data = mediation_demo
))[c("a", "b")]



Simulated Mediation Data for Examples

Description

A simulated dataset for demonstrating medfit's simple, serial, parallel, and treatment-by-mediator interaction workflows with one running example. The data are simulated: they describe no real study, population, or finding.

Usage

mediation_demo

Format

A data frame with 400 rows and 8 variables:

treatment

Integer, 0/1. Randomized treatment assignment.

mediator1

Numeric. First mediator; affected by treatment.

mediator2

Numeric. Serial mediator; affected by treatment and mediator1.

mediator3

Numeric. Parallel mediator; affected by treatment only.

covariate1

Numeric. Continuous confounder of the mediator-outcome relations.

covariate2

Integer, 0/1. Binary confounder of the mediator-outcome relations.

outcome

Numeric. Outcome with no product terms; use it for the simple, serial, and parallel models.

outcome_int

Numeric. outcome plus a treatment by mediator1 interaction; use it only for models with that interaction: the four-way decomposition with a single mediator, or joint effects with several mediators (JointMediationData).

Details

The variables follow a fictional workplace-training story, used only so the examples read concretely: randomized assignment to a training program (treatment) raises skill confidence (mediator1), which builds task mastery (mediator2); the assignment also triggers supervisor check-ins (mediator3); outcome is job performance.

All errors are independent standard normal. The generating equations are

M_1 = 0.5X + 0.3C_1 + 0.3C_2 + e_1

M_2 = 0.2X + 0.5M_1 + 0.2C_1 + e_2

M_3 = 0.5X + e_3

Y = 0.2X + 0.4M_1 + 0.3M_2 + 0.3M_3 + 0.3C_1 + 0.2C_2 + e_4

and outcome_int adds 0.5 X M_1.

Because the covariates confound the mediator-outcome relations, every model should adjust for both covariate1 and covariate2. A model that omits a downstream mediator estimates reduced-form coefficients rather than the structural ones above: for example, the simple model outcome ~ treatment + mediator1 + covariates has limiting coefficients 0.55 for mediator1 and 0.41 for treatment. For a serial model, include mediator1 in the outcome model as well; the serial indirect effect a \times d \times b is then the effect through the chain mediator1 to mediator2 only.

Source

Simulated for package demonstration; not drawn from or representing any real study. The generating script is data-raw/mediation_demo.R in the package source repository.

Examples

data(mediation_demo)
str(mediation_demo)

# Simple mediation, adjusting for both covariates
fit <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)
nie(fit)

Extract Natural Direct Effect (NDE)

Description

Extract the natural direct effect from a mediation analysis result. The NDE represents the effect of treatment on outcome that does NOT operate through the mediator(s).

Usage

nde(x, ...)

Arguments

x

A MediationData, SerialMediationData, ParallelMediationData, InteractionMediationData, or JointMediationData object.

...

Additional arguments passed to methods. For a TwoLevelMediationData, level = c("within", "between", "both") selects the level (within by default).

Details

Without a treatment-by-mediator product (MediationData, SerialMediationData, ParallelMediationData) the NDE is the direct-path coefficient, NDE = c'. With a product it also depends on the mediator's mean under no treatment:

Value

A numeric scalar of class mediation_effect carrying a type attribute.

See Also

nie(), te(), pm(), paths(), decompose()

Examples

med_data <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)

nde(med_data)


Extract Natural Indirect Effect (NIE)

Description

Extract the natural indirect effect from a mediation analysis result. The NIE represents the effect of treatment on outcome that operates through the mediator(s).

Usage

nie(x, ...)

Arguments

x

A MediationData, SerialMediationData, ParallelMediationData, InteractionMediationData, JointMediationData, or BootstrapResult object. For a BootstrapResult, nie() returns the bootstrapped point estimate (with a warning if the statistic was not an NIE).

...

Additional arguments passed to methods. For a SerialMediationData, type = c("chain", "total") selects the chain-specific (default) or the total indirect effect (see Details). For a TwoLevelMediationData, level = c("within", "between", "contrast", "both") selects the level (within is the default; the contrast, within minus between, is descriptive and exists for nie() only). For a TwoLevelParallelMediationData, level as for TwoLevelMediationData and type = c("total", "specific") selects the total indirect effect (default) or one specific indirect effect per mediator.

Details

The effects are for a unit contrast of the treatment. By class:

The "Methods and Formulas" article on the package website gives the full formulas.

Value

A numeric scalar of class mediation_effect carrying a type attribute (a named vector, one value per mediator, for TwoLevelParallelMediationData with type = "specific"). For intervals use confint() or bootstrap_mediation().

See Also

nde(), te(), pm(), paths(), decompose()

Examples

med_data <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)

nie(med_data)


Extract All Path Coefficients

Description

Extract all path coefficients from a mediation analysis result.

Usage

paths(x, ...)

Arguments

x

A MediationData, SerialMediationData, ParallelMediationData, InteractionMediationData, or JointMediationData object.

...

Additional arguments passed to methods

Details

For simple mediation (MediationData):

For serial mediation (SerialMediationData):

For parallel mediation (ParallelMediationData): a1, b1, a2, b2, ..., c_prime.

For InteractionMediationData: a, b, c_prime, and theta3 (the treatment-by-mediator coefficient).

For JointMediationData: the raw coefficients a1..aK, dij, b1..bK, ⁠theta3_<mediator>⁠, and c_prime. The a paths here are the raw coefficients, not the propagated ⁠a*⁠ values used by the effects.

Value

A named numeric vector of path coefficients

See Also

nie(), nde(), te(), pm()

Examples

med_data <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)

paths(med_data)


Extract Proportion Mediated (PM)

Description

Extract the proportion of the total effect that is mediated (operates through the mediator(s)).

Usage

pm(x, ...)

Arguments

x

A MediationData, SerialMediationData, ParallelMediationData, InteractionMediationData, or JointMediationData object.

...

Additional arguments passed to methods. For a TwoLevelMediationData, level = c("within", "between", "both") selects the level (within by default).

Details

PM = \frac{NIE}{TE} = \frac{NIE}{NIE + NDE}

For serial mediation (SerialMediationData) the numerator is the total indirect effect, nie(x, type = "total"), and the denominator the full total effect from te().

The proportion mediated can be:

The ratio has no delta-method standard error in medfit; bootstrap it with bootstrap_mediation() for supported objects. pm() and bootstrap inference refuse data extracted from bounded FIML fits; see fit_sem().

Value

A numeric scalar of class mediation_effect, usually between 0 and 1 (negative or greater than 1 in cases of suppression effects), or NA with a warning when the total effect is numerically zero.

See Also

nie(), nde(), te(), paths()

Examples

med_data <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)

pm(med_data)


Quick Summary of Mediation Results

Description

Print a one-line summary of mediation results, perfect for quick checks or a compact report line.

Usage

quick(x, digits = 3, ...)

Arguments

x

A MediationData or SerialMediationData object (or result from med()). Other classes error; use print() or summary() for them.

digits

Integer: number of significant digits (default: 3)

...

Additional arguments (ignored)

Details

quick() refuses data extracted from bounded FIML fits. Use print(), summary() or tidy() for those objects; see fit_sem() for their limits.

Prints a compact one-line summary showing:

If bootstrap results are available (from med(..., boot = TRUE)), confidence intervals are shown for NIE.

Value

Invisibly returns x

See Also

med(), nie(), nde(), pm()

Examples

result <- med(
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1",
  outcome = "outcome",
  covariates = c("covariate1", "covariate2")
)

# One-line summary
quick(result)


Optimizer settings for the sem engine

Description

Builds the control argument of fit_sem() and mbco_sem() (and of fit_mediation() with engine = "sem", through engine_args = list(control = )). A plain list is still accepted there and keeps its earlier meaning: every entry is an nloptr option, exactly as ⁠sem_control(nloptr = <list>)⁠.

Usage

sem_control(optimizer = "auto", n_starts = NULL, nloptr = list())

Arguments

optimizer

Character: "auto" (default) leaves the algorithm to the engine (SLSQP for a listwise fit, unless nloptr names another algorithm; the fixed SLSQP-plus-nlminb protocol for FIML). "slsqp" requests SLSQP explicitly; it gives the same fit as "auto", and naming a different nloptr algorithm with it is an error. FIML accepts only "auto".

n_starts

Positive integer or NULL (default): the number of starts, as the n_starts argument of fit_sem(). Giving it both here and at the top level is an error unless the two agree. NULL uses the top-level value, or the default of the estimator (5 listwise, 3 for FIML).

nloptr

Named list of options passed to nloptr for a listwise fit (for example list(maxeval = 20000L)). The empty list (default) keeps the engine's options. FIML requires the empty list.

Details

The resolved search protocol of a fit (estimator, the algorithm that ran, the number of starts and the start rule) is recorded in fit@diagnostics$protocol.

A top-level n_starts that differs in value from sem_control(n_starts = ), or optimizer = "slsqp" with a different nloptr algorithm, stops with an error of class medfit_error_sem_control_conflict.

Value

An object of class medfit_sem_control: a list with elements optimizer, n_starts and nloptr.

See Also

fit_sem(), mbco_sem()

Examples

ctl <- sem_control(nloptr = list(maxeval = 20000L))
ctl
fit <- fit_sem("mediator1 ~ a*treatment\noutcome ~ b*mediator1 + cp*treatment",
               mediation_demo, control = ctl)
fit@diagnostics$protocol


Extract Total Effect (TE)

Description

Extract the total effect from a mediation analysis result: the sum of the indirect and direct effects.

Usage

te(x, ...)

Arguments

x

A MediationData, SerialMediationData, ParallelMediationData, InteractionMediationData, or JointMediationData object.

...

Additional arguments passed to methods. For a TwoLevelMediationData, level = c("within", "between", "both") selects the level (within by default).

Details

TE = NIE + NDE

For a SerialMediationData object the total effect is the sum over every directed X-to-Y path in the fitted models: the direct path, the full chain, and every path that skips a mediator (for two mediators, c' + a_1 b_1 + a_2 b_2 + a_1 d_{21} b_2). With the same covariates in every equation and linear models this equals the treatment coefficient of the outcome regressed on the treatment and covariates alone. A path missing from its model counts as zero; when a path is in a model but its coefficient was not recorded (a hand-built object), te() returns NA with a warning. For glm fits with a non-identity link the sum of path products is on the linear-predictor scale, as for MediationData.

Value

A numeric scalar of class mediation_effect carrying a type attribute.

See Also

nie(), nde(), pm(), paths(), decompose()

Examples

med_data <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)

te(med_data)

# Verify: TE = NIE + NDE
nie(med_data) + nde(med_data)


Tidy, Glance, and Inference Methods for medfit Objects

Description

tidy() converts a mediation data object or a BootstrapResult into a tidy tibble, one row per path coefficient or effect. glance() returns a one-row summary. The base generics stats::coef(), stats::vcov(), stats::confint(), and stats::nobs() also have methods for every mediation class; see Details.

Usage

tidy_s7_object(x, ...)

glance_s7_object(x, ...)

Arguments

x

A MediationData, SerialMediationData, ParallelMediationData, InteractionMediationData, JointMediationData, ClusterMediationData, TwoLevelMediationData, BootstrapResult, or SEMFit object (a SEMFit has its own columns; see SEMFit-methods). A TwoLevelMediationData has within and between rows (nie_within, nie_between, nie_contrast, ...); the between effect rows and the contrast are NA with a classed warning when the between level is unidentified (the contrast also when both a and b are equated across levels) (between path rows are NA without one).

...

Passed to the class method: type ("all", "paths", "effects", and for interaction objects "components"), conf_int (logical, add conf_low/conf_high), and conf_level (default 0.95).

Details

Path standard errors are the square roots of the diagonal of ⁠@vcov⁠. Effect standard errors (NIE, NDE, TE, and for interaction objects the four-way components) use the delta method over the full ⁠@vcov⁠, the same computation as confint(parm = "effects"), so tidy(conf_int = TRUE) reproduces confint() exactly. Intervals are normal approximations (\hat{\theta} \pm z \, SE); the sampling distribution of a product of coefficients is skewed, so for inference on indirect effects prefer bootstrap_mediation(). tidy() raises no warning about this; confint() does.

For a serial chain fitted as separate lm/glm regressions, ⁠@vcov⁠ has zero covariances between equations, and the effect standard errors inherit that. The proportion mediated (reported by glance()) has no standard error: it is a ratio whose delta-method standard error is unstable when the total effect is near zero, so bootstrap it instead.

Bounded FIML

For data extracted from a bounded FIML fit, tidy(), coefficients, covariance and normal path/effect intervals are supported, but glance(), pm() and bootstrap intervals refuse. The bootstrap recommendations above apply only to other supported objects. glance() on the source SEMFit instead retains likelihood and information-criterion fields, with model tests unavailable. See fit_sem() for the bounded model, assumptions and inference limits.

Base methods

Value

tidy(): a tibble (a data frame if tibble is not installed) with columns term, estimate, std_error, and, when conf_int = TRUE, conf_low and conf_high.

glance(): a one-row tibble with nie, nde, te, pm, nobs, and converged; interaction objects add interaction and m_star, and joint objects add cde, structure, n_mediators, interactions, and m_star.

See Also

bootstrap_mediation(), MediationData

Examples

med_data <- fit_mediation(
  formula_y = outcome ~ treatment + mediator1 + covariate1 + covariate2,
  formula_m = mediator1 ~ treatment + covariate1 + covariate2,
  data = mediation_demo,
  treatment = "treatment",
  mediator = "mediator1"
)
# tidy() is the generic from the generics package (also re-exported by broom)
generics::tidy(med_data)
generics::tidy(med_data, type = "effects", conf_int = TRUE)


Test equal indirect effects across the two levels of a native two-level fit

Description

[Experimental] Likelihood-ratio test of the null that the within-level and the between-level indirect effects are equal, a_w b_w = a_b b_b, for a native two-level fit from fit_sem() with ⁠cluster =⁠. The statistic is the free fit's likelihood against the fit with that one nonlinear equality. It is a separate test: the descriptive within-minus-between contrast of nie(level = "contrast") is never reported by nie() with a p-value, and there is no Wald test of it here.

Usage

twolevel_equal_indirect(
  object,
  a_within = "a_w",
  b_within = "b_w",
  a_between = "a_b",
  b_between = "b_b",
  n_starts = NULL,
  control = NULL,
  n_boot = 0L,
  seed = NULL
)

Arguments

object

A SEMFit from fit_sem() with ⁠cluster =⁠ (a two-level model).

a_within, b_within

The labels of the within-level (level 1) a and b regression paths.

a_between, b_between

The labels of the between-level (level 2) a and b regression paths.

n_starts, control

Optimizer settings for the constrained refit; NULL keeps the fit's own.

n_boot

Number of parametric bootstrap replications of the statistic (default 0, none). Each replication draws clustered data of the same cluster sizes from the constrained fit, refits both models and keeps the statistic; replications that do not resolve (an inadmissible, non-positive-definite or non-converged refit) are dropped, so the bootstrap p-value is conditional on admissible refits, and the number dropped is reported (boot$n_dropped). The bootstrap p-value is ⁠(1 + #{LR* >= LR}) / (n_valid + 1)⁠; use it at a small number of clusters, where the between-level asymptotics are poor.

seed

Optional integer seed for the bootstrap; the caller's random number state is restored.

Details

The null ⁠a_w b_w = a_b b_b⁠ is a smooth surface except where all four paths are 0, where it is singular. Away from that point the likelihood-ratio statistic is referred to chi-square(1), an asymptotic law in the number of clusters J (the between-level paths rest on J clusters). Near it, and when a level-2 variance is near the boundary, the chi-square(1) law may not hold; no closed-form law is claimed. The function warns when all four free-fit paths are within two standard errors of 0 (class medfit_warning_twolevel_equal_singular) and when a level-2 variance at the constrained fit is below 1% of its implied between plus within variance.

The constrained surface has sign twins: flipping the signs of the within pair (a_w, b_w), the between pair (a_b, b_b) or both leaves the equality satisfied, at a worse likelihood. The optimizer's "the starts disagree" warning is not raised when every disagreeing accepted start is such a twin of the kept fit; the lowest-discrepancy start is kept. Any other disagreement among the starts, and every other optimizer warning, is signaled as usual.

After the refit the pair-sign twins of the kept fit are tried as well (a twin certificate): each flip of a pair with no zero is fitted once from the kept estimates with that flip, and the lowest discrepancy is kept. It is a local search of up to three single-start solves, not a proof of a global optimum: a twin refit that fails is skipped, and the search runs at every n_starts, so a worse twin is not kept with n_starts = 1, where no second start is compared. It changes the statistic only when a twin ends lower. A twin that ends at an inadmissible solution (a level-2 variance on its boundary) or with a covariance matrix that is not positive definite, below the kept discrepancy, makes the result unresolved, as it does with more starts. When the better optimum has a level-2 variance on its boundary the result is therefore unresolved or, with n_starts = 1 in very small samples (about 12 clusters), a non-global optimum, as before the certificate. The row allows eight sign patterns; flipping pairs together reaches the four of the kept fit's orbit. The other orbit does hold local optima: a per-elimination oracle found local optima in both orbits in 30 of 35 small cells (closest gap 0.02 LR). The kept orbit still won every time that was tested (no win from the other orbit in 84 stress cells, 114 QA cells with an all-orthant oracle and 715 constrained fits from signed starts), so the coverage of the other orbit rests on the free-fit-pattern and all-positive default starts: evidence, not a proof. The pair flip is a symmetry of the constraint, not of the likelihood, so the twins are separate local optima. Cost: a call takes about 3 to 4 times as long at n_starts = 1, about twice at the default and about 1.3 times at 30 starts; a bootstrap replicate costs about 2.5 times the engine fits.

The guard admits the equality of any two a-then-b chains with the same x, m and y at levels 1 and 2, so a serial a*d or d*b chain of the same shape is admitted too; only the a*b indirect effect of a single mediator has an oracle and a gate here.

The constrained fit is never trusted blindly: if it ends at an inadmissible solution (a negative variance at either level, a covariance matrix that is not positive definite, class medfit_warning_twolevel_inadmissible), does not converge, or has a lower discrepancy than the free fit, the result is unresolved (statistic and p.value NA, unresolved = TRUE, the reason in note) with a warning, never a likelihood-ratio number. If the fit already carries a nonlinear constraint, or the four paths are not the level-1 and level-2 regressions, the call is refused with class medfit_error_twolevel_unsupported; a single-level fit is medfit_error_twolevel_required.

Value

An object of class c("twolevel_equal_indirect", "htest"): statistic (LR, the scale of mbco_sem()), parameter (df = 1), p.value (chi-square(1)), method, data.name, n_obs, n_clusters, level (c("within", "between")), indirect (the two indirect effects of the free fit and of the constrained fit), unresolved, note, near_singular, twin, and boot (NULL, or a list with statistic, p.value, n_boot, n_valid and n_dropped when n_boot > 0). twin records what the twin certificate did, for resolved and unresolved results: tried (a twin refit was attempted), replaced (a twin replaced the kept fit), flipped (read from the signs of the adopted fit's four path estimates against the kept fit's, not from the start that produced it: "within" or "between" when both paths of that pair changed sign, "other" once for any other sign change, including a path that reaches or leaves zero, and empty when no sign changed, as when the twin is another optimum in the kept fit's sign pattern), f_gain (the kept discrepancy minus the adopted one, 0 if none; the statistic drops by n_obs * f_gain) and unresolved (a better inadmissible or covariance-stage twin made the result unresolved). print() does not show it.

See Also

mbco_sem(), fit_sem(), nie()

Examples


set.seed(1)
id <- rep(1:40, each = 6)
x <- stats::rnorm(40)[id] + stats::rnorm(240)
m <- 0.5 * x + stats::rnorm(40)[id] + stats::rnorm(240)
y <- 0.4 * m + 0.2 * x + stats::rnorm(40)[id] + stats::rnorm(240)
d <- data.frame(cluster = id, X = x, M = m, Y = y)
fit <- fit_sem(
  "level: 1\n M ~ a_w*X\n Y ~ b_w*M + X\nlevel: 2\n M ~ a_b*X\n Y ~ b_b*M + X",
  data = d, cluster = "cluster"
)
twolevel_equal_indirect(fit)



Bootstrap Callback for Two-Level Mediation

Description

Experimental. The interface may change without the usual deprecation period.

Usage

twolevel_statistic(
  x,
  effect = c("nie_within", "nie_between", "nie_contrast", "nde_within", "nde_between",
    "te_within", "te_between", "pm_within", "pm_between", "a_within", "b_within",
    "c_prime_within", "a_between", "b_between", "c_prime_between"),
  treatment = NULL,
  mediator = NULL,
  outcome = NULL,
  level = NULL,
  specific = NULL
)

Arguments

x

A TwoLevelMediationData or TwoLevelParallelMediationData object, or a two-level lavaan fit.

effect

One of "nie_within" (default), "nie_between", "nie_contrast" (within minus between, descriptive), "nde_within", "nde_between", "te_within", "te_between", "pm_within", "pm_between", or a path row: "a_within", "b_within", "c_prime_within", "a_between", "b_between", "c_prime_between". The proportion mediated is NA where the total effect is zero. For several mediators: "nie" (default), "nie_j", "nde" or "te".

treatment, mediator, outcome

Variable names. Required for a lavaan fit; taken from the object for a TwoLevelMediationData or TwoLevelParallelMediationData. mediator is a character vector of length two or more for a fit with several mediators, a character scalar otherwise.

level

For several mediators only: "within" (default), "between" or "contrast". For one mediator the level is part of effect, and level must be left unset.

specific

For effect = "nie_j" only: the name of the mediator whose specific indirect effect is returned.

Details

Builds the scalar statistic_fn that bootstrap_mediation() needs for one effect of a two-level (1-1-1) mediation model, so the within and the between indirect effect and their contrast can be bootstrapped without writing the callback by hand. The form of the callback depends on the first argument:

A refit that errors, does not converge, warns, or leaves the between level unidentified (a treatment or any mediator ICC below getOption("medfit.between_icc_error", 0.01), for a between effect or the contrast; the ICC is the unrestricted (h1) one that lavaan::lavInspect(refit, "icc") reports) is a failed replicate: bootstrap_mediation() excludes it and reports the count in a warning. An inadmissible refit (a negative variance) is kept, as the point estimate keeps it. The covariance checks of the point-estimate extraction are not repeated per refit (no standard errors are computed). Refits skip standard errors, the model test and lavaan's post-check (se = "none", test = "none", check.post = FALSE), which do not change the maximum likelihood estimates; everything else comes from the fit's own call.

Refit environment. The refit re-evaluates the call stored in the fit with data replaced by the resampled data (and, for a model that is not a literal string, with the fit's parameter table). Names that lavaan leaves unevaluated in that call (for example control = ctl or estimator = est) are resolved in the environment that called twolevel_statistic(), captured at that call, not where the fit was made and not where the callback later runs. Create the callback in the scope that holds those objects. Calls written with a namespace, such as lavaan::lavaan() resolve regardless.

The contrast is NA by constraint when both a and b are equated across levels and a between effect is NA when the between level is not identified, so asking for either raises a classed error here instead of returning a distribution of NA.

Several mediators. An invalid level, or level = "contrast" with effect = "nde" or "te", stops with class medfit_error_twolevel_level. An effect not defined for several mediators, effect = "nie_j" without specific or with a name that is not one of the mediators, and specific with another effect stop with class medfit_error_twolevel_unsupported, as do level and specific given for one mediator. A between effect or the contrast of a within-only fit stops with class medfit_between_unidentified, and the contrast of a mediator (for "nie_j") or of every mediator (for "nie") whose a and b are both equated across levels stops with class medfit_error_twolevel_constrained.

Value

A function of one argument returning a number: a named parameter vector for a TwoLevelMediationData or TwoLevelParallelMediationData, a data frame for a lavaan fit.

See Also

bootstrap_mediation(), TwoLevelMediationData, TwoLevelParallelMediationData

Examples


if (requireNamespace("lavaan", quietly = TRUE) && requireNamespace("MASS", quietly = TRUE)) {
  set.seed(1)
  id <- rep(1:60, each = 5)
  x <- stats::rnorm(60)[id] + stats::rnorm(300)
  m <- 0.5 * x + stats::rnorm(60)[id] + stats::rnorm(300)
  y <- 0.4 * m + 0.2 * x + stats::rnorm(60)[id] + stats::rnorm(300)
  d <- data.frame(id = id, X = x, M = m, Y = y)
  model <- "
    level: 1
      M ~ X
      Y ~ M + X
    level: 2
      M ~ X
      Y ~ M + X
  "
  fit <- lavaan::sem(model, data = d, cluster = "id")
  td <- extract_mediation(fit, treatment = "X", mediator = "M", outcome = "Y")
  bootstrap_mediation(twolevel_statistic(td, "nie_between"), method = "parametric",
                      mediation_data = td, n_boot = 200, seed = 1)
  bootstrap_mediation(
    twolevel_statistic(fit, "nie_between", treatment = "X", mediator = "M", outcome = "Y"),
    method = "nonparametric", data = d, cluster = "id", n_boot = 20, seed = 1
  )
}