Is it possible to change syntax for a lavaan model dynamically and programmatically with R objects? I’d like to include the contents of an R object in lavaan syntax. As an example, I’d like to fix parameters to a value specified from an R object. Here is an example: ``` library("lavaan")
sampleSize <- 1000
set.seed(52242)
mydata <- data.frame(matrix(nrow = sampleSize, ncol = 4))
names(mydata) <- c("predictorLatentSEM","criterionLatentSEM","predictorObservedSEM","criterionObservedSEM")
latentCorrelation <- .8
reliabilityPredictor <- .9
reliabilityCriterion <- .85
mydata$predictorLatentSEM <- rnorm(sampleSize, 0 , 1)
mydata$criterionLatentSEM <- latentCorrelation * mydata$predictorLatentSEM + rnorm(sampleSize, 0, sqrt(1 - latentCorrelation ^ 2))
mydata$predictorObservedSEM <- reliabilityPredictor * mydata$predictorLatentSEM + rnorm(sampleSize, 0, sqrt(1 - reliabilityPredictor ^ 2))
mydata$criterionObservedSEM <- reliabilityCriterion * mydata$criterionLatentSEM + rnorm(sampleSize, 0, sqrt(1 - reliabilityCriterion ^ 2))
# This works
model_syntax <- '
# Factor loadings
predictorLatent =~ 1*predictorObservedSEM
criterionLatent =~ 1*criterionObservedSEM
# Factor correlation
criterionLatent ~ predictorLatent
# Residual errors
predictorObservedSEM ~~ (1 - .9^2)*predictorObservedSEM # where .9 is the value of `reliabilityPredictor`
criterionObservedSEM ~~ (1 - .85^2)*criterionObservedSEM # where .85 is the value of `reliabilityCriterion`
'
model_fit <- sem(model_syntax,
data = mydata,
missing = "ML")
# This does not work
model_syntax2 <- '
# Factor loadings
predictorLatent =~ 1*predictorObservedSEM
criterionLatent =~ 1*criterionObservedSEM
# Factor correlation
criterionLatent ~ predictorLatent
# Residual errors
predictorObservedSEM ~~ (1 - reliabilityPredictor^2)*predictorObservedSEM
criterionObservedSEM ~~ (1 - reliabilityCriterion^2)*criterionObservedSEM
'
model_fit2 <- sem(model_syntax2,
data = mydata,
missing = "ML")
``` In the example above, I’d like to fix the residual error of the `predictorObservedSEM` variable to be equal to the value of `(1 - reliabilityPredictor ^ 2)`. However, the lavaan syntax does not seem to allow fixing parameters based on the values from other R objects. In this minimal example, I’m trying to specify a fixed parameter, but It’d be nice to extend this to be able to specify fixed parameters, parameter labels, starting values, which variables load on a factor, etc. programmatically based on the contents of R objects.
Thanks in advance,
Isaac