I have several variables, say X1
to Xn
, and I want to include correlation between each pair of them in my SEM (I use lavaan
package for R software).
I know I can specify
X1 ~~ X2+X3+...+Xn
X2 ~~ X3+X4+...+Xn
X3 ~~ X4+X5+...+Xn
and so on.
Is there any shorter way to achieve this?
If you just want to create the calls, you could try this:
sub("\\+", " ~~ ", sapply(1:10, function(i) paste(paste0("X", i:10), collapse = " + ")))
[1] "X1 ~~ X2 + X3 + X4 + X5 + X6 + X7 + X8 + X9 + X10" "X2 ~~ X3 + X4 + X5 + X6 + X7 + X8 + X9 + X10"
[3] "X3 ~~ X4 + X5 + X6 + X7 + X8 + X9 + X10" "X4 ~~ X5 + X6 + X7 + X8 + X9 + X10"
[5] "X5 ~~ X6 + X7 + X8 + X9 + X10" "X6 ~~ X7 + X8 + X9 + X10"
[7] "X7 ~~ X8 + X9 + X10" "X8 ~~ X9 + X10"
[9] "X9 ~~ X10" "X10"
Perhaps you may want to delete the last element, "X10"
, and of course you could replace 10
by the N
of your data.