Suppose I have a data set df containing data on 2 media variables Fb and TV and Sales as the dependent variable. Now in order to investigate the indirect effect of Facebook on Sales via TV which acts as a mediator variable the following R code is used.
specmod <- "
#Path c (direct effect)
Sales ~ c*Facebook
#Path a
TV ~ a*Facebook
#Path b
Sales ~ b*TV
#Indirect effect (a*b)
ab := a*b
"
set.seed(1214)
fitmod <- sem(specmod, data = df, se = "bootstrap", bootstrap = 100)
parameterEstimates(fitmod, ci = TRUE, level = 0.95, boot.ci.type = "perc")
But if I have 9 media variables and want to check the mediation effect of all the variables then how should I proceed? The predictor and the mediator variable for each model iteration will be different combinations of the media variables. How can I automate the above code with different model iterations.
This is not an elegant solution but it is simple in terms of programming:
First, form the vectors of x-variables and m-variables. Second, use
paste()to create a vector of the model syntax strings. The call tocat()is optional, for verifying the generated model syntax strings. Third, simply uselapply()to fit each of the generated models. If bootstrap CIs are needed, need to setiseedto ensure that the same set of bootstrap samples are used in all models.lavaanhassemList()for fitting a model to a list of datasets. However, I am not aware of a similar function to fit a list of models to the same dataset. If yes, that function can be used in place oflapply().