rlapplymediatorr-lavaan

Create function with direct input into lavaan mediation.model in R


In order to run a mediation model using the lavaan package in R, you have to first create a mediation model using this code:

mediation.model <- ' 
             # mediator
             mediator ~ a*iv
             dv ~ b*mediator
           
             # direct effect
             dv ~  c*iv

           # indirect effect (a*b)
             ab := a*b

           # total effect
             total := c + (a*b)
         '

I am trying to write a function so that I can input specific variables and it'll automatically put them into the model and output the model summary. I have many mediators to test.

This is my current draft of the function, but it doesn't seem to work because the mediation.model part is between parentheses.

med <- function(iv, mediator, dv) {
  mediation.model <- ' 
             # mediator
             mediator ~ a*iv
             dv ~ b*mediator
           
             # direct effect
             dv ~  c*iv

           # indirect effect (a*b)
             ab := a*b

           # total effect
             total := c + (a*b)
         '
  fit <- sem(mediation.model, data = df, meanstructure = TRUE,
           se = "boot", bootstrap = 500)

  return(summary(fit, fit.measures=T, standardized=T, ci=TRUE))
}

How can I modify this so I can input iv (independent variable), mediator, and dv (dependent variable) and get the output of the entire model? I will eventually need to loop this over several mediators (probably using lapply). I am also open to the input of the function only being the "mediator" and putting in the iv and dv manually if necessary.


Solution

  • You can try using paste() to assemble your model syntax.

    med <- function(iv, mediator, dv) {
      stopifnot(inherits(iv, "character"))
      stopifnot(inherits(dv, "character"))
      stopifnot(inherits(mediator, "character"))
    
      mediation.model <- paste0(' 
                 # mediator
                 mediator ~ a*', iv, '
                 ', dv, ' ~ b*', mediator, '
               
                 # direct effect
                 ', dv, ' ~  c*', iv, '
    
               # indirect effect (a*b)
                 ab := a*b
    
               # total effect
                 total := c + (a*b)
             ')
      fit <- sem(mediation.model, data = df, meanstructure = TRUE,
               se = "boot", bootstrap = 500)
    
      return(summary(fit, fit.measures=T, standardized=T, ci=TRUE))
    }
    

    Note that lavaan's model.syntax need not be a single character string, but can be a character vector (e.g., each specified parameter can be 1 element in the vector).