During the next 12 days, I will learn and repeat the basics
of structural equation modeling (SEM) using lavaan and semPlot packages in R.
You can search my lavaan posts by typing: #UsmanZafarParacha_lavaan
, and semPlot posts by typing: #UsmanZafarParacha_semPlot
============
During this day, essential libraries, including lavaan and
semPlot are loaded. Then, an SEM model is specified showing how diet and
exercise affect cardiovascular disease both directly and indirectly through
mental health. Following lines of codes can be used:
library(lavaan)
library(semPlot)
# Model specification
model <- '
# Direct effects
mental_health ~ diet
+ exercise
cardiovascular_disease ~ diet + exercise + mental_health
# Indirect effects
(via mental health)
cardiovascular_disease ~ mental_health
'
Then a supposed data is generated using the following lines
of codes:
set.seed(123)
n <- 200 # number
of participants
# Simulate data
diet <- rnorm(n, mean = 50, sd = 10)
exercise <- rnorm(n, mean = 30, sd = 8)
mental_health <- 0.4 * diet + 0.6 * exercise + rnorm(n)
cardiovascular_disease <- 0.5 * diet + 0.3 * exercise +
0.7 * mental_health + rnorm(n)
# Combine into a data frame
data <- data.frame(diet, exercise, mental_health,
cardiovascular_disease)
Then the lavaan function is used to fit the specified model
to the data, using the following lines of codes:
fit <- sem(model, data = data)
# View the summary of the results
summary(fit, standardized = TRUE, fit.measures = TRUE)
Then, the SEM can be visualized using the semPlot using the
following lines of codes:
# Create a SEM plot
semPaths(fit, whatLabels = "std", layout =
"tree", edge.label.cex = 1.2,
sizeMan = 7,
sizeLat = 10, asize = 2, color = "lightblue")
Source:
ChatGPT
No comments:
Post a Comment