Package semMediation is an extension of package lavaan. The main functions of package semMediation are as follows:
You can install semMediation
package via github.
install.packages("devtools")
devtools::install_github("cardiomoon/semMediation")
Consider a classical mediation setup with four variables: Y is the dependent variable, X is the predictor, and M1 and M2 are mediators. For illustration, we create a toy dataset containing these four variables, and fit a path analysis model that includes the direct effect of X on Y and the indirect effect of X on Y via M1 or M2 and second indirect effect via M1 and M2.
set.seed(1234)
X <- rnorm(100)
M1 <- 0.5*X + rnorm(100)
M2 <-0.6*X + rnorm(100)
Y <- 0.3*M1 + 0.4*M2 + rnorm(100)
data <- data.frame(X = X, Y = Y, M1 = M1, M2 = M2)
str(data)
'data.frame': 100 obs. of 4 variables:
$ X : num -1.207 0.277 1.084 -2.346 0.429 ...
$ Y : num -0.7323 -0.7088 0.3375 0.2245 0.0679 ...
$ M1: num -0.189 -0.336 0.608 -1.675 -0.611 ...
$ M2: num -0.239 0.863 0.836 -0.707 0.569 ...
To make a mediatino equation, you can use makeEquation() function.
require(lavaan)
require(semPlot)
require(semMediation)
model=makeEquation(X="X",M=c("M1","M2"),Y="Y")
cat(model)
# Mediation Effect
Y~b1*M1+b2*M2+c1*X
M1~a1*X
M2~a2*X+d1*M1
ind1:=a1*b1
ind2:=a2*b2
secondInd1:=a1*d1*b2
total1:=c1+a1*b1+a2*b2+a1*d1*b2
fit=sem(model,data=data)
summary(fit)
lavaan (0.5-20) converged normally after 15 iterations
Number of observations 100
Estimator ML
Minimum Function Test Statistic 0.000
Degrees of freedom 0
Minimum Function Value 0.0000000000000
Parameter Estimates:
Information Expected
Standard Errors Standard
Regressions:
Estimate Std.Err Z-value P(>|z|)
Y ~
M1 (b1) 0.449 0.100 4.483 0.000
M2 (b2) 0.423 0.108 3.917 0.000
X (c1) 0.062 0.132 0.472 0.637
M1 ~
X (a1) 0.474 0.103 4.613 0.000
M2 ~
X (a2) 0.636 0.104 6.093 0.000
M1 (d1) 0.088 0.092 0.957 0.339
Variances:
Estimate Std.Err Z-value P(>|z|)
Y 1.046 0.148 7.071 0.000
M1 1.054 0.149 7.071 0.000
M2 0.898 0.127 7.071 0.000
Defined Parameters:
Estimate Std.Err Z-value P(>|z|)
ind1 0.213 0.066 3.215 0.001
ind2 0.269 0.082 3.295 0.001
secondInd1 0.018 0.019 0.911 0.362
total1 0.562 0.121 4.652 0.000
To visualize model, you can use semPaths() function from semPlot package. But, semPaths() function is in appropriate for models with two or more mediators.
semPaths(fit)
mediationPlot() can visualize models with multiple mediators, multiple independent variables and/or multiple dependent variables.
mediationPlot(fit)
You can show standardized parameter estimates(default) or parameter estimates(est), or names(name) by settting the parameter “whatLabels”.
mediationPlot(fit,whatLabels = "name")
mediationPlot(fit,whatLabels = "est")
You can visualize indirect effects of this model.
mediationPlot(fit,regression=FALSE,correlation=FALSE,indirect=TRUE)
You can also visualize seconary indirect effect of this model.
mediationPlot(fit,regression=FALSE,correlation=FALSE,secondIndirect=TRUE)