set.seed(1)
n <- 300
A <- rbinom(n, 1, 0.5)
C <- rnorm(n)
M <- 0.5 * A + 0.3 * C + rnorm(n)
Y <- 0.4 * M + 0.2 * A + 0.1 * C + rnorm(n)
dat <- data.frame(A, M, Y, C)mediationverse does not define its own mediate() function. The entry point already exists upstream: medfit::med() takes a data frame and three variable names and returns a fitted mediation object. The other packages then work on that same object.
This article runs one complete analysis in four calls:
medfit::med().RMediation.probmed.medfit is attached with library(mediationverse); the code below calls it with medfit:: so it runs the same either way. RMediation and probmed are optional, so each of their calls is guarded and is skipped when the package is not installed.
A binary treatment A, a mediator M, an outcome Y and one covariate C. The true indirect effect is 0.5 x 0.4 = 0.2.
set.seed(1)
n <- 300
A <- rbinom(n, 1, 0.5)
C <- rnorm(n)
M <- 0.5 * A + 0.3 * C + rnorm(n)
Y <- 0.4 * M + 0.2 * A + 0.1 * C + rnorm(n)
dat <- data.frame(A, M, Y, C)fit <- medfit::med(
dat,
treatment = "A",
mediator = "M",
outcome = "Y",
covariates = "C"
)
fitMediationData object
====================
Path coefficients:
a (X -> M): 0.4755
b (M -> Y|X): 0.4355
c' (X -> Y|M): 0.2472
Indirect (a*b): 0.2071
Variables:
Treatment: A
Mediator: M
Outcome: Y
Model info:
N observations: 300
Converged: Yes
Source: stats::glm
Residual SDs:
Mediator model: 1.0879
Outcome model: 1.0485
Extractors return single effects: medfit::nie(fit) (natural indirect), medfit::nde(fit) (natural direct), medfit::te(fit) (total) and medfit::pm(fit) (proportion mediated). For bootstrap inference add boot = TRUE, n_boot = 1000, seed = 123 to the call.
RMediation::ci_mediation_data() accepts the fitted object directly and uses the distribution of the product by default.
if (requireNamespace("RMediation", quietly = TRUE)) {
RMediation::ci_mediation_data(fit, level = 0.95)
}$CI
[1] 0.09453523 0.33518924
$Estimate
[1] 0.2070642
$SE
[1] 0.06140013
probmed::pmed() also accepts the fitted object. Pmed is the probability that the mediator shift leaves a random individual better off.
if (requireNamespace("probmed", quietly = TRUE)) {
set.seed(2)
probmed::pmed(fit)
}
P_med: Probability of Mediated Shift
====================================
Estimate: 0.55
95% CI: [ 0.519 , 0.58 ]
Indirect Effect (Product of Coefficients):
Estimate: 0.205
95% CI: [ 0.0898 , 0.33 ]
Inference: parametric_bootstrap
Bootstrap samples: 1000
Treatment contrast: X = 1 vs. X* = 0
Interpretation:
P(Y(1, M(1)) > Y(1, M(0))) = 0.55
P that the mediator shift (M(0) -> M(1)) leaves a random individual better off, holding X = 1.
mediationverse_sitrep() shows which of these packages are installed and current; mediationverse_news() shows what changed in each.vignette("mediationverse-workflow") extends this to sensitivity analysis and simulation.