Written and maintained by CASRAI Editorial Board
Published
On this page
Mediation analysis in R evaluates whether the statistical association between an independent predictor variable and a dependent outcome variable operates through an intermediate intervening mechanism known as a mediator. Researchers conduct mediation analysis in R primarily through two complementary frameworks: the counterfactual causal mediation approach implemented in the mediation package, and the structural equation modeling path-analytic framework implemented in the lavaan package. These tools allow researchers to estimate direct and indirect causal pathways, compute robust nonparametric bootstrap confidence intervals, accommodate nonlinear generalized models, and evaluate model sensitivity against unmeasured confounding.
What mediation analysis in R is used for in research
In empirical scientific inquiry, establishing whether an intervention or exposure predicts an outcome represents only the initial step of causal discovery. Investigators across psychology, epidemiology, health services, sociology, and political science deploy mediation analysis to uncover the generative behavioral, psychological, or biological pathways connecting causes to effects. A researcher studying an educational intervention seeks to establish not merely whether participation improves examination performance, but whether improved study habits or reduced academic anxiety explains the observed gain. Statistically testing such hypotheses requires isolating the indirect effect transmitted through the mediator from the direct effect operating independently of that intermediate variable.
Historically, mediation modeling relied on the causal-steps regression criteria introduced by Baron and Kenny in 1986. Under that classical paradigm, researchers fit three separate ordinary least squares regression equations: predicting the mediator from the exposure, predicting the outcome from the exposure, and predicting the outcome simultaneously from the exposure and mediator. However, modern methodological literature—including seminal evaluations published in PubMed Central by MacKinnon, Fairchild, and Fritz (2007)—demonstrated critical deficiencies in the causal-steps approach. The classical method exhibits low statistical power, fails to provide a single quantitative inferential test for the indirect effect, and incorrectly assumes that the product of two regression coefficients follows a normal Gaussian distribution. Furthermore, traditional regression fails when mediators or outcomes are categorical, binary, or count-based.
To overcome these methodological limitations, modern statistical practice in R relies on two primary computational architectures. The first is the potential outcomes causal framework formulated by Kosuke Imai, Luke Keele, Dustin Tingley, and Teppei Yamamoto (2010), implemented in the Comprehensive R Archive Network package mediation. This framework formalizes the Average Causal Mediation Effect (ACME) and the Average Direct Effect (ADE) using counterfactual definitions that hold across linear models, logistic regressions, survival models, and generalized additive specifications. The second framework is covariance-based structural equation modeling (SEM) executed through Yves Rosseel’s lavaan package, which estimates simultaneous path systems, accommodates multiple parallel or sequential mediators, and integrates measurement models for latent variables. For broader theoretical context on causal definitions, see our guide on causal mediation analysis, or review the foundational properties of intervening variables in our explainer on what is a mediator variable.
How to install or access mediation packages in R
Mediation analysis in R utilizes open-source libraries hosted on the official Comprehensive R Archive Network (CRAN). To prepare a clean, reproducible computing environment, open an active R session (version 4.0.0 or higher recommended) or RStudio interface and execute the standard installation command for the foundational libraries:
install.packages(c("mediation", "lavaan", "robmed", "psych"))
Once installation finishes, load the packages into your working environment using the library() function. The mediation package imports necessary linear algebra and optimization utilities, while lavaan initializes compiled routines for high-performance matrix manipulation and structural equation estimation:
library(mediation)
library(lavaan)
library(robmed)
library(psych)
To confirm that package binaries and documentation compiled without errors, verify their installed versions against the CRAN repository records. As documented by Tingley et al. (2014) in the Journal of Statistical Software, the mediation package operates seamlessly across Linux, macOS, and Windows operating systems without requiring external commercial compilers or proprietary matrix libraries.
How to run mediation analysis in R step by step
Conducting a rigorous mediation workflow requires estimating intermediate regression parameters, calculating the indirect product, and deriving resampling-based confidence intervals. The following six steps demonstrate the complete computational workflow using both the counterfactual mediation library and the structural equation lavaan library.
- Prepare the Data and Inspect Variable Distributions: Ensure that your analysis dataframe contains no unstructured missingness across your independent variable (X, treatment or exposure), mediator (M), dependent variable (Y, outcome), and baseline covariates (C). Verify that continuous variables do not exhibit severe skewness or multi-sigma outliers that could distort ordinary least squares estimators.
- Specify and Fit the Regression Sub-Models: In the
mediationpackage framework, you first fit the mediator model and the outcome model as separate statistical objects using standard R modeling functions such aslm()for continuous outcomes orglm()for generalized linear outcomes. Specify the mediator regression and outcome regression as follows:fit_mediator = lm(mediator ~ treatment + covariate1 + covariate2, data = research_data) fit_outcome = lm(outcome ~ treatment + mediator + covariate1 + covariate2, data = research_data) - Execute the Causal Mediation Function: Combine the two fitted model objects using the
mediate()function. Specify the exact variable names assigned to the treatment and mediator arguments. To calculate robust inferential intervals without making normality assumptions regarding the product distribution, setboot = TRUEand configure the number of resampling simulations (such assims = 1000):set.seed(42) mediation_results = mediate( model.m = fit_mediator, model.y = fit_outcome, treat = "treatment", mediator = "mediator", boot = TRUE, sims = 1000 ) - Specify and Estimate the Structural Equation Model in lavaan: When your research design requires simultaneous path modeling, latent constructs, or multiple mediators, specify the paths within a single syntax string. Use parameter labels (such as
a,b, andcp) and define the indirect and total effects explicitly using the colon-equals operator:lavaan_syntax = ' mediator ~ a * treatment + covariate1 outcome ~ b * mediator + cp * treatment + covariate1 indirect_effect := a * b total_effect := cp + (a * b) ' set.seed(42) fit_lavaan = sem( model = lavaan_syntax, data = research_data, se = "bootstrap", bootstrap = 1000 ) - Test for Treatment-Mediator Interaction: Conventional mediation models assume that the effect of the mediator on the outcome remains invariant across treatment conditions. To test whether the treatment moderates the mediator effect, include an interaction term in the outcome model and execute the
test.TMint()function provided by themediationpackage:fit_outcome_int = lm(outcome ~ treatment * mediator + covariate1, data = research_data) results_int = mediate(fit_mediator, fit_outcome_int, treat = "treatment", mediator = "mediator", boot = TRUE, sims = 1000) test.TMint(results_int)If the interaction test proves statistically significant, report moderated mediation rather than a simple invariant indirect effect. For comprehensive guidance on modeling interaction parameters, consult our guide on mediation analysis methods and reporting and our comparative review of mediator vs moderator configurations.
- Conduct Sensitivity Analysis for Unmeasured Confounding: The identification of causal mediation rests on the sequential ignorability assumption: given baseline covariates, treatment assignment is statistically independent of potential outcomes and mediators, and the observed mediator is conditionally independent of potential outcomes. Because researchers cannot randomize the mediator directly, unobserved mediator-outcome confounders may bias estimates. Use the
medsens()function to evaluate how sensitive your findings are to hidden confounding:sens_analysis = medsens(mediation_results, rho.by = 0.05, sims = 1000) summary(sens_analysis) plot(sens_analysis)
How to read the output
Interpreting mediation output requires distinguishing point estimates from their inferential bootstrap confidence bounds. Calling summary(mediation_results) on a fitted mediate object generates a standardized terminal report organized into four primary metrics:
Causal Mediation Analysis
Nonparametric Bootstrap Confidence Intervals with the Percentile Method
Estimate 95% CI Lower 95% CI Upper p-value
ACME 0.2140 0.0821 0.3644 p below 0.001
ADE 0.3420 0.1120 0.5890 p = 0.004
Total Effect 0.5560 0.2840 0.8310 p below 0.001
Prop. Mediated 0.3849 0.1582 0.7420 p below 0.001
Sample Size Used: 450
Simulations: 1000
Each row represents a specific structural component of the causal architecture:
- ACME (Average Causal Mediation Effect): Represents the indirect effect transmitted through the mediator (analogous to the product of coefficients a × b in linear path models). It quantifies how much the outcome would change on average if the treatment remained fixed while the mediator shifted from the value it would realize under the control condition to the value it would realize under the treated condition. In this output, the ACME estimate is 0.2140 with a 95% bootstrap confidence interval spanning from 0.0821 to 0.3644. Because this confidence interval does not cross zero, the indirect mediation pathway is statistically significant.
- ADE (Average Direct Effect): Represents the direct effect of the exposure on the outcome unmediated by the intervening variable (analogous to path c’). It quantifies the expected change in the outcome when treatment status changes while holding the mediator constant at the level naturally induced under the baseline condition. Here, the ADE is 0.3420 (95% CI: 0.1120 to 0.5890, p = 0.004), demonstrating that a substantial direct effect persists alongside the mediated path.
- Total Effect: Represents the overall effect of the exposure on the outcome, calculated as the sum of the mediated effect and the direct effect (Total = ACME + ADE). In linear systems, this corresponds to path c from the unadjusted bivariate regression. In this model, the total effect is 0.5560 (95% CI: 0.2840 to 0.8310).
- Prop. Mediated (Proportion Mediated): Quantifies the fraction of the total exposure effect accounted for by the indirect pathway, computed as ACME divided by the Total Effect (0.2140 / 0.5560 = 0.3849, or 38.5%). Researchers must exercise caution when interpreting this ratio: if ACME and ADE have opposite mathematical signs (indicative of competitive mediation or suppression), the proportion mediated can become negative or exceed 1.0, rendering percentage interpretations misleading.
When reviewing output from lavaan via summary(fit_lavaan, standardized = TRUE, ci = TRUE), inspect the Defined Parameters section. Look for the rows labeled indirect_effect and total_effect. Focus primarily on the columns labeled ci.lower and ci.upper. Consistent with the methodological guidance in MacKinnon et al. (2007), researchers should report whether the 95% bootstrap confidence interval encompasses zero rather than relying solely on asymptotic symmetric Wald z-tests. If your workflow bridges path modeling and macro syntax, compare these outputs with our reference guide on Hayes’ PROCESS macro model numbers and reporting and our structural guide on path analysis.
In the sensitivity analysis output generated by summary(sens_analysis), examine the critical threshold value of the correlation parameter rho at which the ACME estimate equals zero. The parameter rho represents the correlation between the error terms of the mediator model and the outcome model. If ACME becomes zero only at substantial values of rho (such as absolute values exceeding 0.40), researchers can conclude that substantial unobserved confounding would be required to overturn the detected mediation effect.
Troubleshooting mediation analysis in R
Researchers routinely encounter estimation hurdles when fitting empirical mediation models in R. Below are standard diagnostic protocols for addressing four common technical difficulties.
- Addressing Model Non-Convergence and Resampling Terminations: Nonparametric bootstrapping requires refitting both sub-models hundreds or thousands of times across resampled data matrices. If a resampled dataset contains zero variance in a binary variable or severe multicollinearity between covariates, individual bootstrap iterations can fail or throw singularity errors. To prevent silent crashes in script execution, set a constant random number seed prior to execution (
set.seed(12345)). Inlavaan, adjust the optimizer settings by passing control parameters or specifying robust standard error algorithms such asse = "robust.sem". - Resolving Missing Data Discrepancies Across Sub-Models: By default,
lm()andglm()drop observations with missing values listwise across the variables included in that specific formula. If the outcome model contains covariates with missing values that do not appear in the mediator model, the two models will estimate parameters across differing sample sizes. Themediate()function detects this discrepancy and aborts with an error indicating that sample sizes do not match. Resolve this by performing complete-case filtering on the combined analysis dataframe before model estimation (for example, usingcomplete_data = na.omit(raw_data[, c("Y", "M", "X", "C")])), or by using Full Information Maximum Likelihood inlavaanvia the argumentmissing = "fiml". - Managing Binary and Categorical Variables: When the mediator or outcome is dichotomous (binary 0/1), linear regression models violate homoscedasticity and distributional assumptions. In the
mediationpackage, pass a logistic model fitted viaglm()with binomial family and logit link. Because the product-of-coefficients method (a × b) breaks down mathematically across different logit link scales, themediate()function calculates ACME using numerical simulation across the potential outcomes response surface, ensuring mathematically valid scale integration. - Mitigating Extreme Outliers and Heavy Tails: Outlying observations can severely inflate or attenuate ordinary least squares regression estimates. When data exploration reveals multivariate outliers, use the
robmedpackage developed by Alfons, Ates, and Groenen (2022). Thefit_Mediation()function inrobmedexecutes robust MM-estimation paired with a fast and robust bootstrap algorithm, ensuring that contaminated observations do not generate spurious mediation findings.
Free alternatives to mediation packages in R
While the mediation and lavaan packages serve as the primary workhorses for causal and structural mediation workflows in R, several complementary open-source packages and standalone software suites offer specialized capabilities for distinct research designs. The data table below compares the primary software packages available within the R statistical environment, detailing their primary theoretical orientation, supported estimation engines, resampling features, and specialized functionality.
| Software Package | Primary Framework | Estimation Engine | Resampling Support | Key Strengths and Limitations |
|---|---|---|---|---|
| mediation (Tingley et al.) | Counterfactual Causal Mediation | Linear, Generalized Linear, and Additive Models (lm, glm, gam) | Nonparametric Bootstrap and Quasi-Bayesian Monte Carlo | Gold standard for unmeasured confounding sensitivity analysis (medsens); specialized for single mediator systems. |
| lavaan (Rosseel) | Structural Equation Modeling (SEM) | Maximum Likelihood (ML, MLM, MLR), GLS, and WLS | Nonparametric Bootstrap (percentile and BCa CIs) | Unmatched flexibility for multiple parallel or sequential mediators, latent constructs, and full measurement models. |
| robmed (Alfons et al.) | Robust Regression Mediation | S- and MM-Estimators with Huber and Tukey loss functions | Fast and Robust Bootstrap (ROBMED) | Protects parameter estimates against multivariate leverage points and severe outliers in mediator or outcome. |
| psych (Revelle) | Ordinary Least Squares Path Analysis | Bivariate and Multiple Ordinary Least Squares Regression | Empirical and Nonparametric Percentile Bootstrap | Rapid exploratory mediation testing; integrates seamlessly with personality and psychometric test scale analysis. |
| mma (Yu and Li) | Multiple Mediation Analysis | Nonparametric and Semiparametric Regression Models | Nonparametric Resampling | Specialized for testing hundreds of high-dimensional potential mediators simultaneously (such as genomics and microbiome data). |
Beyond scripting in R, researchers can access open-source standalone statistical environments that wrap these underlying libraries. JASP and jamovi are free, graphical user interface (GUI) software applications that run lavaan and mediation under the hood, allowing researchers to generate publication-grade mediation analyses and bootstrap tables through menu-driven interfaces without writing R syntax directly. For researchers working in legacy environments, Andrew Hayes’ PROCESS macro provides an alternative script-based tool for SPSS, SAS, and R, though it remains restricted to observed variables and does not support latent SEM structures.
Frequently asked questions
What are the main packages used for mediation analysis in R?
The two most widely used packages for mediation analysis in R are mediation and lavaan. The mediation package, developed by Dustin Tingley and colleagues, specializes in causal mediation analysis under the potential outcomes framework, accommodating nonlinear models and sensitivity analyses for unmeasured confounding. The lavaan package, developed by Yves Rosseel, specializes in structural equation modeling (SEM), making it the preferred choice when models involve latent variables, multiple parallel or sequential mediators, or complex covariance structures. Specialized alternatives include robmed for outlier-resistant mediation and psych for rapid exploratory testing.
How do I run a basic mediation model using the mediation package?
To run a basic mediation model using the mediation package, first fit the mediator model predicting the mediator from the treatment and covariates using lm() or glm(). Second, fit the outcome model predicting the outcome from the mediator, treatment, and covariates. Third, combine both fitted objects using the mediate() function, specifying the treatment and mediator variable names, and set boot = TRUE with sims = 1000 to generate nonparametric bootstrap confidence intervals. Finally, inspect the results using summary() to evaluate the Average Causal Mediation Effect (ACME) and Average Direct Effect (ADE).
What is the difference between Baron and Kenny and modern causal mediation?
The classical Baron and Kenny (1986) approach is a causal-steps regression method that evaluates whether individual path coefficients meet statistical significance thresholds in sequence. In contrast, modern causal mediation formalizes effects using counterfactual potential outcomes, explicitly defining the Average Causal Mediation Effect (ACME) and Average Direct Effect (ADE). Modern causal mediation does not require a statistically significant total effect, natively handles binary and nonlinear variables without scaling artifacts, provides unified bootstrap confidence intervals, and incorporates formal sensitivity analysis to test for unmeasured confounding.
Why should I use bootstrapping instead of the Sobel test?
Bootstrapping is strongly preferred over the Sobel test because the sampling distribution of the indirect effect (the product of two regression coefficients, a × b) is almost always skewed and non-normal, even when sample sizes are moderately large. The Sobel test assumes a symmetric Gaussian distribution, which leads to artificially wide confidence intervals, inflated Type II error rates, and reduced statistical power. Nonparametric bootstrapping repeatedly resamples the empirical dataset to construct empirical, asymmetric confidence intervals that accurately reflect the true underlying distribution without imposing normality assumptions.
Can ACME be significant when the total effect is not?
Yes, the Average Causal Mediation Effect (ACME) can be statistically significant even when the total effect is not statistically significant. This condition frequently occurs in competitive mediation or suppression designs, where the direct effect (ADE) and the indirect effect (ACME) operate in opposite directions with opposing mathematical signs. When the direct and indirect pathways cancel each other out, the net total effect shrinks toward zero, yet the underlying mediated causal mechanism remains real, detectable, and statistically robust.
How do I test for sensitivity to unmeasured confounding?
In the mediation package, test for sensitivity to unmeasured confounding by applying the medsens() function to your fitted mediate object. The function calculates how point estimates and confidence intervals for ACME vary as a function of the correlation parameter rho, which represents the correlation between the error terms of the mediator and outcome models. Reviewing the threshold value of rho at which ACME encompasses zero indicates how strong an unmeasured confounder would have to be to nullify the observed mediation effect.
Sources
- Comprehensive R Archive Network (CRAN): Package mediation, checked 2026-11-22
- Journal of Statistical Software: mediation: R Package for Causal Mediation Analysis (Tingley et al., 2014), checked 2026-11-22
- Comprehensive R Archive Network (CRAN): Package lavaan, checked 2026-11-22
- Journal of Statistical Software: lavaan: An R Package for Structural Equation Modeling (Rosseel, 2012), checked 2026-11-22
- Comprehensive R Archive Network (CRAN): Package robmed, checked 2026-11-22
- PubMed Central (PMC): A Comparison of Methods to Test Mediation and Other Intervening Variable Effects (MacKinnon et al., 2007), checked 2026-11-22
Data: R Mediation Analysis Package Specifications and Parameter Capabilities
Comparative specifications of primary R mediation analysis libraries compiled from official CRAN documentation and peer-reviewed software publications.
Period covered: 2012/2026. Coverage: Global.
| Package Name | Primary Framework | Estimation Engine | Resampling Methods | Unmeasured Confounding Sensitivity | Latent Variable Modeling |
|---|---|---|---|---|---|
| mediation | Causal potential outcomes (Imai et al.) | Linear, Generalized Linear, and Additive Models (lm, glm, gam) | Nonparametric bootstrap and quasi-Bayesian Monte Carlo simulation | Built-in medsens function via residual correlation parameter rho | No (requires observed manifest variables) |
| lavaan | Covariance-based Structural Equation Modeling | Maximum Likelihood (ML, MLM, MLR), Generalized Least Squares, and WLS | Nonparametric bootstrap standard errors and percentile or BCa CIs | No direct automated function (requires phantom variable coding) | Full latent variable SEM and measurement model integration |
| robmed | Robust MM-regression and outlier filtering | Robust S- and MM-estimators with redescending psi loss functions | Fast and robust bootstrap (ROBMED) algorithm | Robust weight diagnostic filtering for high leverage outliers | No (restricted to manifest variables) |
| psych | Ordinary least squares path analysis | Standard multivariable linear regression equations | Empirical and nonparametric percentile bootstrapping | None built-in | Principal components and exploratory factor analysis scores |
| mma | Multiple and high-dimensional mediation | Nonparametric and semiparametric regression models | Nonparametric bootstrap resampling | Nonlinear interaction sensitivity tests across multiple mediators | No (restricted to manifest variables) |
Sources
- CRAN: Package mediation (accessed 2026-11-22)
- mediation: R Package for Causal Mediation Analysis (Tingley et al., 2014) (accessed 2026-11-22)
- CRAN: Package lavaan (accessed 2026-11-22)
- lavaan: An R Package for Structural Equation Modeling (Rosseel, 2012) (accessed 2026-11-22)
- CRAN: Package robmed (accessed 2026-11-22)
- A Comparison of Methods to Test Mediation and Other Intervening Variable Effects (MacKinnon et al., 2007) (accessed 2026-11-22)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







