library(lavaan)
data(simple_med)
dat <- simple_med
mod <-
"
m ~ a*x
y ~ b*m
ab := a*b
"
fit_med <- sem(mod, simple_med, fixed.x = FALSE)
parameterEstimates(fit_med)
# A trivial example for verifying the results
my_ab <- function(object) {
# Need to use lav_model_get_parameters()
# because the object is only a modified
# lavaan-object, not one directly
# generated by lavaan function
est <- lavaan::lav_model_get_parameters(object@Model, type = "user")
unname(est[1] * est[2])
}
# Check the function
my_ab(fit_med)
coef(fit_med, type = "user")["ab"]
# Create the function
my_userp <- gen_userp(func = my_ab,
sem_out = fit_med)
# Try it on the vector of free parameters
my_userp(coef(fit_med))
# Generate a modified lavaan model
fit_userp <- gen_sem_out_userp(userp = my_userp,
userp_name = "my_userp",
sem_out = fit_med)
# This function can then be used in the model syntax.
# Note that the following example only work when called inside the
# workspace or inside other functions such as ci_bound_ur()`
# and `ci_bound_ur_i()` because `lavaan::sem()` will
# search `my_userp()` in the global environment.
# Therefore, the following lines are commented out.
# They should be run only in a "TRUE" interactive
# session.
# mod2 <-
# "
# m ~ x
# y ~ m
# ab := my_userp()
# "
# fit_med2 <- sem(mod2, simple_med, fixed.x = FALSE)
# parameterEstimates(fit_med2)
#
# # Fit the model with the output of the function, a*b
# # fixed to .50
#
# fit_new <- fit_userp(.50)
#
# # Check if the parameter ab is fixed to .50
# parameterEstimates(fit_new)
Run the code above in your browser using DataLab