简体   繁体   中英

How can I add a value from a list or dataframe to the lavaan syntax?

When specifying a model in lavaan, it is possible to fixate certain variables. For example we can assume an monotonic increase in relationship of X (latent factor) from y1 (observation) through y5. This syntax would look as follows:

model <- '
X =~ 1*y1 + 2*y2 + 3*y3 + 4*y4 + 5*y5 '

sem(model ...)

This works perfectly. Yet I would like to add a second value from a list or df. The sytax works when I add the value manually, yet not if I try to acess it in a list...

###this works
model <- '
X =~ 0.5*1*y1 + 0.46*2*y2 + 0.45*3*y3 + 0.43*4*y4 + 0.56*5*y5 '


###this doesnt
values <- c(0.5,0.46,0.45,0.43,0.56)

model <- '
X =~ values[1]*1*y1 + values[2]*2*y2 + values[3]*3*y3 + values[4]*4*y4 + values[5]*5*y5 '

I also tried adding the values to the data I am running the model with, and then adressing the variable name... but it does not work.

Does anyone have any further suggestions on what I could try?

As Terrence Jorgensen has notedhere , " lavaan 's model syntax is just a character string/vector, so you can use paste() to assemble it or add quantities that are stored in other objects."

Here's how you would do that in your example:

model <- paste0("X =~ ", values[1], "*1*y1 + ", values[2], "*2*y2 + ", values[3], "*3*y3 + ", values[4], "*4*y4 + ", values[5], "*5*y5")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM