Skip to content

Instantly share code, notes, and snippets.

@dermatologist
Created October 17, 2018 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dermatologist/fbbd9e196660e390c84967f68a25bbf0 to your computer and use it in GitHub Desktop.
Save dermatologist/fbbd9e196660e390c84967f68a25bbf0 to your computer and use it in GitHub Desktop.
Structural Equation Modeling in R with output as LaTeX tables.
library("lavaan")
library(xtable)
options(xtable.floating = FALSE)
options(xtable.timestamp = "")
DM.data = read.csv("C:\\data.csv", header = TRUE)
DM.model <- '
# Measurement model Ref: http://lavaan.ugent.be/
# Model: http://lavaan.ugent.be/tutorial/figure/sem.png
# latent variables
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem65 =~ y5 + y6 + y7 + y8
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
# residual covariances
y1 ~~ y5
y2 ~~ y4 + y6
y3 ~~ y7
y4 ~~ y8
y6 ~~ y8
'
## capture all the output to a file.
zz <- file("results.txt", open = "wt")
sink(zz)
sink(zz, type = "output")
fit <- sem(DM.model, data = DM.data)
print ("Partition Table")
print ("")
xtable(parTable(fit))
print ("Summary Table")
print ("")
summary(fit)
print ("Parameter Estimates")
print ("")
xtable(parameterEstimates(fit))
print ("Standardized Solution")
print ("")
xtable(standardizedSolution(fit))
print ("Fitted or implied model")
print ("")
fitted(fit)
print ("Unstandardized Residuals of the fitted model")
print ("")
resid(fit)
print ("Standardized Residuals of the fitted model")
print ("")
resid(fit, type= "standardized")
print ("Normalized Residuals of the fitted model")
print ("")
resid(fit, type= "normalized")
print ("Fit Measures")
print ("")
fitMeasures(fit)
print ("Model Modification Indices")
print ("")
mi <- modindices(fit)
xtable(mi[mi$op == "=~",])
print ("Model matrices")
print ("")
inspect(fit)
print ("Starting Values")
print ("")
inspect(fit, what = "start")
print ("Internal representation of model in Lavaan")
print ("")
xtable(inspect(fit, what = "list"))
sink(type = "output")
sink()
file.show("results.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment