Skip to content

Instantly share code, notes, and snippets.

@mkearney
Created August 27, 2019 14:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mkearney/eb8f4a6cc94680d8bfda94ee62c7e9c5 to your computer and use it in GitHub Desktop.
Save mkearney/eb8f4a6cc94680d8bfda94ee62c7e9c5 to your computer and use it in GitHub Desktop.
Example of a three-variable cross lagged panel model in R using {lavaan}
## generate data set
x2 <- rnorm(200)
x1 <- x2 + rnorm(200)
y2 <- rnorm(200) + x2
y1 <- y2 + rnorm(200)
z2 <- rnorm(200) + y2
z1 <- z2 + rnorm(200)
d <- data.frame(x1, x2, y1, y2, z1, z2)
## specify null and full models
null_mod_syntax <- '
x2 ~ 0*x1 + 0*y1 + 0*z1
y2 ~ 0*x1 + 0*y1 + 0*z1
z2 ~ 0*x1 + 0*y1 + 0*z1
'
full_mod_syntax <- '
x2 ~ x1 + y1 + z1
y2 ~ x1 + y1 + z1
z2 ~ x1 + y1 + z1
'
## estimate models
m0 <- lavaan::sem(null_mod_syntax, data = d)
m1 <- lavaan::sem(full_mod_syntax, data = d)
## compare models (see degrees of freedom)
lavaan::anova(m0, m1)
## view full model summary
lavaan::summary(m1)
## compare DV correlations...
with(d, cor(data.frame(x2, y2, z2)))
## with residual correlations
subset(
lavaan::parameterEstimates(m1),
op == "~~" & lhs %in% c("x2", "y2", "z2")
)
@yellowbridge
Copy link

Thanks a lot !Can you give a reference for this method?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment