Help with moderated mediation analysis

270 views
Skip to first unread message

Sandra King

unread,
Feb 20, 2025, 2:49:32 AM2/20/25
to lavaan
Hello,
Please, I need urgent help with the moderated mediation analysis I am conducting. I have included the codes below. Predictors are latent variables, mediator is continuous, moderator and outcome variables  are binary (0/1).
First, I did the mediation analysis:
modermd < - "
gnts=~ dis1 + dis2 + dis3 + dis4 +dis4+dis6
knts =~ pub1 + pub2 + pub3
Ints  =~ img1 + img2 + img3
  #mediation
  totdp ~ a1*gnts+ a2*knts+ a3*Ints
  #outcomes
  TRT_Ad ~c1*gnts+ c2*knts+ c3*Ints
  + b1*totdp + age
 #Indirect effects
  a1b1 := a1*b1        
  a2b1 := a2*b1        
  a3b1 := a3*b1
#Total effects
c1a1 := c1 + a1b1  
  c2a2 := c2 + a2b1  
  c3a3 := c3 + a3b1
"
TRT_FIT = sem(modermd, data = ADH_analtbl,
              ordered = "TRT_Ad ",
              estimator = "DWLS")
summary(TRT_FIT, fit.measures = T)
bootfit_fit<- sem(modermd, data = ADH_analtbl,
                    ordered = "TRT_Ad ",
                    se = "bootstrap", bootstrap = 5000, estimator = "DWLS",
                    verbose = TRUE)
parameterEstimates(bootfit_fit, boot.ci.type = "bca.simple", standardized = TRUE, ci=TRUE)

The analysis was ran successfully, and the model fit indices showed good fit. From the results, only one of the latent predictor variables (Ints -> totdp -> TRT_Ad) demonstrated significant mediation. Therefore, for this path, I plan to perform a moderated mediation analysis, with the moderator variable (provcat) being binary (0/1). I included it as a numeric variable since Lavaan does not permit including it as a factor in the analysis. Given that the predictor is a latent variable, I utilized the indprod function from the semTools package to create the interaction terms needed for the moderated mediation analyses, as outlined below:

df_moderated <- indProd(ADH_analtbl, var1 =1img1:img3, var2 = provt, match=F, residualC = T)

#final analysis
modmediated_md <- "
  #measurement model
  Ints  =~ img1 + img2 + img3
  #interaction terms created with indProd
  asper =~ img1.provt + img2.provt + img3.provt
  #Structural regression model
   totdp ~ a1*Ints + a2*provcat + a3*asper
 #outcomes
  ART_Adherence ~ c1*Ints + b1*totanx + age  
  a1b1 := a1*b1        #Indirect effect
  Ca1 := c1 + a1b1  #total effect
  ##Index of Moderated Mediation
  IndexOfTRT := a3*b1
"
bootfit_fit <- sem(modermd, data = df_moderated,
                    ordered = "TRT_Ad ",
                    se = "bootstrap", bootstrap = 5000, estimator = "DWLS",
                    verbose = TRUE)
parameterEstimates(bootfit_fit, boot.ci.type = "bca.simple", standardized = TRUE, ci=TRUE)

I would like to confirm whether my approach is correct, particularly regarding the interaction for the analysis, as I’ve come across mixed opinions on this matter and the more I read online about it I get confused. Specifically, I want to know if utilizing the indProd with residual centering is an appropriate method for handling the interaction between the latent variable and observed variable. If it is not, what would be the best way to address this?

I would greatly appreciate any assitance. Thanks!

g.c.w.ri...@gmail.com

unread,
Feb 20, 2025, 3:42:02 AM2/20/25
to lav...@googlegroups.com

I was wondering whether running in JASP wouldn’t be easier, which generates an R-script which can be attuned then if you wish?

Gert

--
You received this message because you are subscribed to the Google Groups "lavaan" group.
To unsubscribe from this group and stop receiving emails from it, send an email to lavaan+un...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/lavaan/72947bbc-8f6d-4b4e-8a4e-8e5b0cba7fefn%40googlegroups.com.

Christian Arnold

unread,
Feb 20, 2025, 3:57:56 AM2/20/25
to lav...@googlegroups.com
Since your moderator is binary you could use a multi-group model..

HTH

From: lav...@googlegroups.com <lav...@googlegroups.com> on behalf of Sandra King <ekperek...@gmail.com>
Sent: Thursday, February 20, 2025 4:10:01 AM

To: lavaan <lav...@googlegroups.com>
Subject: Help with moderated mediation analysis
--
Message has been deleted

g.c.w.ri...@gmail.com

unread,
Feb 20, 2025, 4:35:43 AM2/20/25
to lav...@googlegroups.com

OK; it is so easy sometimes to run starting models, and then move into R when you need to finetune your model.

 

From: lav...@googlegroups.com <lav...@googlegroups.com> On Behalf Of Sandra King
Sent: donderdag 20 februari 2025 10:31
To: lavaan <lav...@googlegroups.com>
Subject: Re: Help with moderated mediation analysis

 

 I am not familiar with JASP. Additionally, I am using a secured server that does not have JASP installed, and individual installation of applications/programs is not permitted. Thank you for the suggestion.  

Sandra King

unread,
Feb 20, 2025, 4:36:37 AM2/20/25
to lavaan
@Gert , Thank you your response. I am not familiar with JASP. Additionally, I am using a secured server that does not have JASP installed, and individual installation of applications/programs is not permitted. 

On Thursday, February 20, 2025 at 3:42:02 AM UTC-5 g.c.w.ri...@gmail.com wrote:

Sandra King

unread,
Feb 20, 2025, 5:26:03 AM2/20/25
to lavaan
Thank you @ Christian for the suggestion. I am still learning SEM, so I have some questions about the MG-SEM approach you suggested. If I use this method, do I simply add group = "provt" when fitting the model, like this?  

bootfit_fit <- sem(modermd, data = df_moderated, group = "provt",  

                    ordered = "TRT_Ad",  
                    se = "bootstrap", bootstrap = 5000,  
                    estimator = "DWLS", verbose = TRUE)

Do I need to include any equality constraints?
Also, with MG-SEM, I assume there won’t be any interaction terms in the code (and the moderated mediation index wouldn’t be calculated), so I would just interpret the mediation results separately for each group. Is that correct? 

Christian Arnold

unread,
Feb 20, 2025, 5:59:03 AM2/20/25
to lavaan
Hi Sandra,

the first step is to test for invariance (equivalence). If you only want to compare the regression coefficients, you should at least test for configural and metric invariance. If you are also interested in mean differences, it would also make sense to test for scalar invariance. There are various approaches for this. I personally like this one: https://pubmed.ncbi.nlm.nih.gov/29172611/

In this very simple example (which does not exactly correspond to your model), the moderator is tested using a self-defined parameter:

library(lavaan)

# Simulate some data
pop.model.g1 <- "
IV =~ 1 * x1 + 1 * x2 + 1 * x3
DV =~ 1 * y1 + 1 * y2 + 1 * y3
DV ~ 0.2 * IV"

pop.model.g2 <- "
IV =~ 1 * x1 + 1 * x2 + 1 * x3
DV =~ 1 * y1 + 1 * y2 + 1 * y3
DV ~ 0.6 * IV"

n <- c(100, 100)
data <- cbind(
  group = c(rep(1, n[1]), rep(2, n[2])),
  rbind(
    simulateData(pop.model.g1, sample.nobs = n[1], empirical = TRUE),
    simulateData(pop.model.g2, sample.nobs = n[2], empirical = TRUE)
  )
)

# Specify the model
model <- "
IV =~ x1 + x2 + x3
DV =~ y1 + y2 + y3
DV ~ c(b.g1,b.g2) * IV
mod := b.g2 - b.g1
"

fit <- sem(model, data, group = "group", group.equal = "loadings")
parameterEstimates(fit)


The result is something like this:

   lhs op       rhs block group label est    se     z pvalue ci.lower ci.upper
...
47 mod := b.g2-b.g1     0     0   mod 0.4 0.200 2.000  0.045    0.008    0.792



HTH

Christian

Sandra King

unread,
Feb 20, 2025, 3:00:40 PM2/20/25
to lavaan

Hello Dr. Christian,


Thank you very much for your assistance with this issue. I followed your suggestion and tested for measurement invariance. The results indicated that the measurement is equivalent across the groups.                      

#Configural invariance

cfa.Configural <- sem(modmed, data=data_clean, std.lv=T,

                      group = "provt")

# Metric (weak) invariance

cfa.metric<- sem(modmed, data=data_clean, std.lv=T,

                 group = "provt",

                 group.equal = "loadings")

#Scalar (strong) invariance

cfa.scalar <- sem(modmed, data=data_clean, std.lv=T,

                   group = "provt ",

                  group.equal = c("loadings","intercepts"))

fitmeasures(cfa.Configural, c("cfi", "tli"))

cfi tli

  1 1    

fitmeasures(cfa.metric, c("cfi", "tli"))

  cfi tli

0.999 0.998

fitmeasures(cfa.scalar, c("cfi", "tli"))

  cfi tli

0.999 0.998

Scaled Chi-Squared Difference Test (method = “satorra.bentler.2001”)

lavaan NOTE:

    The “Chisq” column contains standard test statistics, not the

    robust test that should be reported per model. A robust difference

    test is a function of two standard (not robust) statistics.

                          Df AIC BIC Chisq Chisq diff Df diff Pr(>Chisq)

cfa.Configural 0 4488.3 4565.1 0.0000                              

cfa.metric          2 4486.6 4554.8 2.2414 1.7396 2 0.4190

cfa.scalar 4 4484.8 4544.5 4.5070 2.2782 2 0.3201


I then went ahead to  run the MG-SEM model below for mediation analysis to compare the regression coefficients:


#final analysis

modmediated_lv2 <- "

Ints  =~ img1 + img2 + img3

totdp ~ c(a1,a2)*Ints

ART_Adherence ~ Ints + c(b1,b2)*totanx + age  


#Defining new parameters

a1b1 := a1 * b1        #Indirect effect for group 1 and group 2

a2b2 := a2 * b2

 modmed := a1b1 - a2b2  # Moderated mediation index (I'm not sure if this is correct since my goal is to conduct a moderated mediation analysis and not just the moderation; I assume the moderated moderation difference as to be between the indirect effects.)#

"

#fit the model

final_fit2 <- sem(modmediated_lv2, data_clean, group = "provt",

                 ordered = "TRT_Ad ",

                 estimator = "DWLS",

                 group.equal = "loadings")


Also, the model ran well and demonstrated a good fit. However, there is an issue with the bootstrapping process, as I received an error message when I ran the code below:


MGSEM_boot _fit <- sem(modmediated_lv2, data_clean, group = "provt",

                             ordered = "TRT_Ad ",

                            se = "bootstrap", bootstrap = 5000, estimator = "DWLS",

                            group.equal = "loadings")

                             verbose = TRUE)

parameterEstimates(MGSEM_boot _fit, boot.ci.type = "bca.simple", standardized = TRUE, ci=TRUE)

...Error in lavaanify(model = FLAT, constraints = constraints, varTable = lavdata@ov, :

  lavaan ERROR: wrong number of arguments in modifier (a1,a2) of element totanxscore~inter_latent

In addition: Warning message:

In lav_options_set(opt) :

  lavaan WARNING: information will be set to “expected” for estimator = “DWLS”

>

It appears that the issue is with the labeling in the code, which was done to test the moderated mediation. My question is: how do I run the bootstrap for MG-SEM to obtain the bias-corrected confidence intervals to report.


Thank you once again for your incredible help!


Best, 

Sandra

Christian Arnold

unread,
Feb 21, 2025, 4:51:59 AM2/21/25
to lavaan

Hi Sandra,

depending on your objective, you can also insert "moderator.a := a2 - a1" and/or moderator.b := b2 - b1". About the problem with the bootstrap: To be honest, I don't immediately see where the problem lies (maybe someone else will notice it?). However, there are a few facets that seem strange to me: (1) Your DV is “ART_Adherence” according to the model specification, but you pass the argument ordered = “TRT_Ad ”. I can't find "TRT_Ad" in the syntax. The error message refers to “totanxscore~inter_latent”. I can't find that in your syntax either. There I only find “totdp ~ c(a1,a2)*Ints”. Something seems strange here. In the very first step, I would look at what R has actually stored in the "modmediated_lv2" object: cat(modmediated_lv2).


HTH

Christian

Sandra King

unread,
Feb 21, 2025, 6:33:51 AM2/21/25
to lavaan

Hi Dr. Christian,
I apologize for the mistake in the code from my previous message. I was typing quickly and didn't notice that. The code was entered correctly in R, as shown below, and that produced the error message. As for the moderation, the "moderator.a := a2 - a1" aligns better with my objective because it reflects the path that is being moderated. Thanks for the suggestion.
The issue I'm facing is with the bootstrapping, which fails to run due to labeling (i.e., c(a1, a2), c(b1, b2)) needed to obtain the path coefficient for each group. When I remove the label or include only a single label (either a1/b1 or a2/b2), the code runs without errors; however, the result is the overall regression coefficient estimate instead of getting separate estimates for Group 1 and Group 2.
Is there any way to obtain the bootstrap estimates and confidence intervals for each group while also being able to estimate the moderated mediation index?

Thank you!


#Analysis code

modmediated_lv2 <- "

inter_latent =~ img1 + img2 + img3

totanxscore ~ c(a1,a2)*inter_latent

TRT_Ad  ~  inter_latent   + c(b1,b2)* totanxscore  + age  


#Defining new parameters

a1b1 := a1 * b1        #Indirect effect for group 1 and group 2

a2b2 := a2 * b2

modmed := a2 - a1   # Moderated mediation index

"

MGSEM_boot _fit <- sem(modmediated_lv2, data_clean, group = "provt",

                             ordered = "TRT_Ad ",

                            se = "bootstrap", bootstrap = 5000, estimator = "DWLS",

                            group.equal = "loadings")

                             verbose = TRUE)


...Error in lavaanify(model = FLAT, constraints = constraints, varTable = lavdata@ov, :

  lavaan ERROR: wrong number of arguments in modifier (a1,a2) of element totanxscore~inter_latent

In addition: Warning message:

In lav_options_set(opt) :

  lavaan WARNING: information will be set to “expected” for estimator = “DWLS”

Christian Arnold

unread,
Feb 21, 2025, 7:19:46 AM2/21/25
to lavaan
I do not know - sorry. However, there are still several typos in your syntax:


MGSEM_boot _fit <- sem(modmediated_lv2, data_clean, group = "provt",

                             ordered = "TRT_Ad ",

                            se = "bootstrap", bootstrap = 5000, estimator = "DWLS",

                            group.equal = "loadings")

                             verbose = TRUE)


Actually, you should not get any results at all because an object name cannot contain spaces.. The model and the bootstrap runs without problems (using simulated data):

# Some data
pop.model.g1 <- "
inter_latent =~ 1 * img1 + 1 * img2 + 1 * img3
totanxscore ~ 0.3 * inter_latent
TRT_Ad ~ 0.4 * inter_latent + 0.2 * totanxscore  
"
pop.model.g2 <- "
inter_latent =~ 1 * img1 + 1 * img2 + 1 * img3
totanxscore ~ 0.3 * inter_latent
TRT_Ad ~ 0.2 * inter_latent + 0.2 * totanxscore  
"
n <- c(200, 200)
data_clean <- cbind(
  provt = c(rep(1, n[1]), rep(2, n[2])),

  rbind(
    simulateData(pop.model.g1, sample.nobs = n[1], empirical = TRUE),
    simulateData(pop.model.g1, sample.nobs = n[2], empirical = TRUE)
  )
)

# Quick and dirty ....
data_clean$TRT_Ad <- sapply(data_clean$TRT_Ad, function(x, TRT_Ad) {
  if(x > median(TRT_Ad)) 1 else 0
}, data_clean$TRT_Ad)


modmediated_lv2 <- "
inter_latent =~ img1 + img2 + img3
totanxscore ~ c(a1,a2) * inter_latent
TRT_Ad ~ inter_latent + c(b1,b2) * totanxscore  
a1b1 := a1 * b1
a2b2 := a2 * b2
modmed := a2 - a1
"

MGSEM_boot_fit <- sem(
  modmediated_lv2,
  data_clean,
  group = "provt",
  ordered = "TRT_Ad",
  se = "bootstrap",
  bootstrap = 50,
  estimator = "DWLS",
  group.equal = "loadings",
  verbose = TRUE
)

parameterEstimates(MGSEM_boot_fit, boot.ci.type = "bca.simple")


I would look at the grouping variable. Looks like something is wrong there.

Sandra King

unread,
Feb 21, 2025, 12:45:07 PM2/21/25
to lavaan
Dear Dr. Christian,
 
It finally worked! I realized that in my actual R code there was no spaces but the bootstrapping did not run because I omitted the group statement (group = "provt"), even though I had correctly included it in my question here. I am immensely grateful for your time and patience in helping me work through this problem.

Here is the final result from the bootstrap:
Defined Parameters:
                              Estimate  Std.Err  z-value  P(>|z|)   ci.lower ci.upper  
    a1b1                     -0.037    0.059   -0.635    0.526     -0.183    0.095          
    a2b2                    -0.188    0.098   -1.923    0.054     -0.467   -0.050        
    modmed             -0.776    0.888   -0.874    0.382     -2.671    0.934
I would like to confirm that since the modmed CI is not significant, indicating that that indirect effects do not significantly differ between the two groups, there is no need to further report the estimates of each indirect effect, even if one of the indirect path CIs is significant? I should only report the modmed CI?

Toby

unread,
Feb 23, 2025, 7:30:14 PM2/23/25
to lav...@googlegroups.com
Hi all,

This is slightly left-of-field. Just out of curiosity - I understand that one can check for between group differences in constructs in lavaan

ie for testing between group mean differences in depression:

Difference := InterceptDeprGr1 - InterceptDeprGr2

I was wondering whether there was capacity in lavaan to test whether such differences are explained by (mediated by) group differences in another variable as well?



Christian Arnold

unread,
Feb 24, 2025, 8:08:13 AM2/24/25
to lavaan
Hi Toby,

I'm not entirely sure if I understand your question correctly, so please take my answer with a grain of salt.

For a two group model, the mean difference of the latent variable (Y) is, in principle, identical to the result of a regression where the group variable (X or group, as you label it) serves as the IV and the latent variable (Y) as the DV. Differences may occur under certain circumstances, depending on the level of invariance.

Suppose you have another latent variable (M) that acts as a mediator between the group variable and Y. You can interpret the multi-group model as follows:

(1) The mean difference of M corresponds to the direct effect of X (group) on M.
(2) The direct effect of X (group) on Y is the mean difference of Y.
(3) The direct effect of M on Y is part of the model.

Accordingly, you can determine the indirect and total effect of X on Y as in a typical mediator model (with X as an exogenous variable). Does this roughly answer your question?

Here is a small example (hopefully without typos):

library(lavaan)

# Simulate some data
pop.model.g1 <- "
M =~ 1 * x1 + 1 * x2 + 1 * x3
Y =~ 1 * y1 + 1 * y2 + 1 * y3
Y ~ 0.4 * M"

pop.model.g2 <- "
M =~ 1 * x1 + 1 * x2 + 1 * x3
Y =~ 1 * y1 + 1 * y2 + 1 * y3
Y ~ 0.4 * M
M ~ 0.3 * 1
Y ~ 0.5 * 1"


n <- c(100, 100)
data <- cbind(
  group = c(rep(1, n[1]), rep(2, n[2])),
  rbind(
    simulateData(pop.model.g1, sample.nobs = n[1], empirical = TRUE),
    simulateData(pop.model.g2, sample.nobs = n[2], empirical = TRUE)
  )
)


# Regression
model <- "
Y =~ y1 + y2 + y3
Y ~ group"
fit <- sem(model, data)
pe <- parameterEstimates(fit)
pe[pe$op == "~",]

# Mean difference
model <- "
Y =~ y1 + y2 + y3
Y~ c(0, NA) * 1"
fit <- sem(model, data, group = "group", group.equal = c("loadings", "intercepts"))
pe <- parameterEstimates(fit)
pe[pe$op == "~1",]


# Same for mediation
model <- "
M =~ x1 + x2 + x3
Y =~ y1 + y2 + y3
M ~ a * group
Y ~ b * M + c * group
ind := a * b
tot := ind + c"

fit <- sem(model, data)
pe <- parameterEstimates(fit)
pe[pe$op %in% c("~", ":="),]

# MG approach
model <- "
M =~ x1 + x2 + x3
Y =~ y1 + y2 + y3
M ~ c(m.0, a) * 1
Y ~ b * M
Y ~ c(m.0, c) * 1
m.0 == 0
ind := a * b
tot := ind + c"

fit <- sem(model, data, group = "group", group.equal = c("loadings", "intercepts"))
pe <- parameterEstimates(fit)
pe[pe$op %in% c("~", "~1", ":="),]
Reply all
Reply to author
Forward
0 new messages