Busabase
Busabase is an open-source (MIT) database and workspace for AI agents — data, docs, skills, and apps in one place. Run it locally, self-host it inside your network, or use Busabase Cloud, and turn age
翻译准备中
This is the repository for the RMediation package.
翻译准备中
取自仓库 README
正在加载完整 README。
查看完整 README ↗RMediation computes confidence intervals for indirect effects in mediation analysis. It implements statistically rigorous methods that account for the non-normal distribution of the product of regression coefficients—addressing the well-known limitations of normal-theory approaches like the Sobel test.
The package supports:
The core confidence-interval methods run in the browser through the mediation-apps Shiny front end—no R installation required:
medci()ci(type = "mc") and ci(type = "asymp")Useful for quick checks, teaching, and for collaborators who do not use R.
Traditional methods (e.g., Sobel test) assume the indirect effect ab follows a normal distribution. This assumption is often violated because the product of two normal variables is not normally distributed—especially when effect sizes are small or sample sizes are modest.
RMediation provides methods that correctly handle this non-normality:
| Method | Best For | Speed |
|---|---|---|
| DOP (Distribution of Product) | Two- and three-variable products; publication-quality results | Fast |
| Monte Carlo | Complex models; 4+ variable products | Moderate |
| MBCO (Model-Based Constrained Optimization) | Hypothesis testing; bootstrap inference | Slower |
install.packages("RMediation")
CRAN serves the stable 1.6.1. Release 1.9.0 is published on GitHub only, as a pre-release; it is not on CRAN.
# Using pak (recommended)
pak::pak("Data-Wise/[email protected]")
# Or using remotes
remotes::install_github("Data-Wise/rmediation", ref = "v1.9.0")
For the development branch, use @dev or ref = "dev" instead.
The development version is also published at the Data-Wise r-universe as a prebuilt binary (no compiler needed):
install.packages(
"RMediation",
repos = c("https://data-wise.r-universe.dev", "https://cloud.r-project.org")
)
When you have coefficient estimates and standard errors (e.g., from a published study):
library(RMediation)
# Path coefficients: a = 0.5 (SE = 0.08), b = 0.6 (SE = 0.04)
# Compute 95% CI for the indirect effect ab
medci(mu.x = 0.5, mu.y = 0.6,
se.x = 0.08, se.y = 0.04,
rho = 0, type = "dop")
#> $`95% CI`
#> [1] 0.2010806 0.4053620
#>
#> $Estimate
#> [1] 0.3
#>
#> $SE
#> [1] 0.05209837
For models with multiple sequential mediators (X → M₁ → M₂ → Y), use the ci() function with a formula:
# Four-path indirect effect: b1 * b2 * b3 * b4
ci(c(b1 = 1.0, b2 = 0.7, b3 = 0.6, b4 = 0.45),
Sigma = c(0.05, 0, 0, 0, # Covariance matrix (lower triangle)
0.05, 0, 0,
0.03, 0,
0.03),
quant = ~ b1 * b2 * b3 * b4,
type = "MC",
n.mc = 1e5)
RMediation integrates directly with lavaan SEM models:
library(lavaan)
library(RMediation)
# Define mediation model with labeled paths
model <- '
m ~ a*x
y ~ b*m + c*x
# Define indirect effect
ab := a*b
'
fit <- sem(model, data = mydata)
# Compute CI for indirect effect (auto-detects 'ab := a*b')
ci(fit, type = "dop")
For serial chains (X → M1 → M2 → Y), let medfit
fit the model and extract the coefficients + covariance, then pass the result
straight to ci(). medfit is an optional (Suggests) dependency.
library(RMediation)
# medfit extracts a SerialMediationData object from a lavaan or lm/glm fit...
mu <- medfit::extract_mediation(
fit, treatment = "X", mediator = c("M1", "M2"), outcome = "Y"
)
# ...and RMediation computes the CI for the serial indirect effect a * d1 * b
ci(mu, level = 0.95, type = "MC")
See vignette("serial-mediation-with-medfit") for the full lavaan and lm/glm
workflow.
For sequential indirect effects of the form a1 * a2 * b (e.g., X → M1 → M2 → Y),
use ProductNormal3 and its exact pprodnormal3() CDF:
library(RMediation)
# Path coefficients and their joint covariance
mu <- c(a1 = 0.5, a2 = 0.4, b = 0.6)
Sigma <- diag(c(0.01, 0.01, 0.01)) # independent paths
# Exact 95% CI for the a1*a2*b sequential indirect effect
pn3 <- ProductNormal3(mu = mu, Sigma = Sigma)
ci(pn3, level = 0.95)
#> lower upper
#> 0.04797581 0.21980280
# Direct CDF query
pprodnormal3(q = 0, mean = mu, cov = Sigma) # P(a1*a2*b <= 0)
Requires RMediation >= 1.7.0. Earlier versions return wrong values when the
a1/a2covariance is ill-conditioned — silently, and without a diagnostic. Strongly correlated path estimates are ordinary in mediation models, so this affects realistic input.
For programmatic use, create ProductNormal objects directly:
# Define distribution of two correlated normal variables
pn <- ProductNormal(
mu = c(0.5, 0.3),
Sigma = matrix(c(0.01, 0.002,
0.002, 0.01), 2, 2)
)
# Compute confidence interval
ci(pn, level = 0.95, type = "dop")
# Get CDF and quantiles
cdf(pn, q = 0.15)
dist_quantile(pn, p = 0.975)
# View summary
summary(pn)
mbco(h0, h1) compares a fitted restricted model (h0) with its full
model (h1). OpenMx models support asymptotic and bootstrap tests; see ?mbco
for clean-start product-null construction and bootstrap arguments.
For a product null (a*b = 0), use mbco_product_null() rather than one
nonlinear constraint. A single constraint can land on the wrong branch, and OpenMx
can silently drop an equality constraint whose Jacobian is zero at the starting
values (OpenMx/OpenMx#433). When
mbco() finds that h0 came back identical to h1 although its constraint was
violated, it refits h0 and warns with class RMediation_constraint_not_enforced;
the warning cannot tell this cause from a violation within the feasibility
tolerance.
Two medfit SEMFit objects support asymptotic comparisons with medfit >=
0.8.0 (GitHub/r-universe), without OpenMx:
d <- as.data.frame(RMediation::memory_exp)
d$x <- as.numeric(d$x) - 1
syntax <- paste("repetition ~ a1*x", "imagery ~ a2*x",
"recall ~ cp*x + b1*repetition + b2*imagery", sep = "\n")
full <- medfit::fit_sem(syntax, d)
null <- medfit::fit_sem(paste(syntax, "a1*b1 == 0", sep = "\n"), d)
RMediation::mbco(null, full) # statistic 0.0831, df 1, p = 0.7731
medfit fits each product-zero branch from clean starts and selects the smallest discrepancy. RMediation compares the fitted pair without refitting, retains medfit's compatibility checks, and refuses ordinary chi-square p-values for active tested bounds. Bootstrap types and OpenMx fitting controls are not supported for SEMFit pairs. The analyst remains responsible for substantive nesting and a valid reference distribution for other nonlinear restrictions.
ml_omitted_confounder() shows how an unmeasured, standardized confounder of
the mediator-outcome relation, described by its correlations with the treatment,
mediator and outcome, would change the between- and within-cluster indirect
effects of a two-level (1-1-1) model. See
vignette("omitted-confounder-sensitivity").
R <- matrix(c(1, .3, .2, .3, 1, .4, .2, .4, 1), 3)
res <- ml_omitted_confounder(
between = list(a = 0.3, b = 0.4, cor = R, sd = c(1, 1, 1)),
r_za = c(0, 0.1)
)
res
plot(res, r_za = 0.1)
The default screen keeps only admissible (positive-definite) grid points; use
screen = "none" to reproduce the published tables.
| Function | Purpose |
|---|---|
medci() | CI for product of two normal variables |
ci() | CI for any function of parameters (formulas, lavaan, ProductNormal, ProductNormal3) |
mbco() | Asymptotic and OpenMx bootstrap MBCO hypothesis tests |
mbco_product_null() | MBCO test of a product null (a*b = 0, serial products) as an intersection-union test over single-path nulls, avoiding the wrong-branch failure of one nonlinear constraint |
ml_omitted_confounder() | Sensitivity of two-level (1-1-1) indirect effects to an omitted confounder (Tofighi & Kelley, 2016) |
ci_mediation_data(), ci_serial_mediation_data() | CI for a medfit MediationData or SerialMediationData object (also reached through ci()) |
pprodnormal() | CDF of product of two normals |
qprodnormal() | Quantiles of product of two normals |
dprodnormal() | Exact density of the product of two normals |
pprodnormal3() | Exact CDF of product of three normals (a1*a2*b) |
dprodnormal3() | Exact density of the product of three normals |
pMC(), qMC() | Monte Carlo CDF and quantile for any function of coefficient estimates |
ProductNormal() | S7 class for two-variable product distributions |
ProductNormal3() | S7 class for three-variable sequential indirect effects |
RMediation is part of the mediationverse—a suite of R packages for comprehensive mediation analysis:
| Package | Purpose |
|---|---|
| mediationverse | Meta-package: install and load all packages |
| medfit | Model fitting and coefficient extraction |
| probmed | Probabilistic effect size (P_med) |
| RMediation | Confidence intervals (DOP, Monte Carlo, MBCO) |
| medrobust | Sensitivity analysis |
| medsim | Simulation infrastructure |
Install the entire ecosystem:
pak::pak("Data-Wise/mediationverse")
library(mediationverse) # Loads all packages
If you use RMediation in your research, please cite:
Tofighi, D., & MacKinnon, D. P. (2011). RMediation: An R package for mediation
analysis confidence intervals. Behavior Research Methods, 43, 692-700.
https://doi.org/10.3758/s13428-011-0076-x
For Monte Carlo CIs in SEM:
Tofighi, D., & MacKinnon, D. P. (2016). Monte Carlo confidence intervals for
complex functions of indirect effects. Structural Equation Modeling: A
Multidisciplinary Journal, 23, 194-205.
https://doi.org/10.1080/10705511.2015.1057284
For sequential mediation and CI method comparisons:
Tofighi, D., & Kelley, K. (2020). Indirect effects in sequential mediation
models: Evaluating methods for hypothesis testing and confidence interval
formation. Multivariate Behavioral Research, 55(2), 188-210.
https://doi.org/10.1080/00273171.2019.1618545
For MBCO and bootstrap methods:
Tofighi, D., & Kelley, K. (2020). Improved inference in mediation analysis:
Introducing the model-based constrained optimization procedure.
Psychological Methods, 25(4), 496-515. https://doi.org/10.1037/met0000259
Tofighi, D. (2020). Bootstrap model-based constrained optimization tests of
indirect effects. Frontiers in Psychology, 10, 2989.
https://doi.org/10.3389/fpsyg.2019.02989
GPL-3