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, I loaded lavaan and semPlot packages. Then,
defined the model using the following lines of codes:
# Define the SEM model
model <- '
# Direct effects
achievement ~
teaching_quality + peer_support + engagement
# Indirect effects
engagement ~
peer_support
# Covariances
(optional if you want to assess relationships between predictors)
peer_support ~~
teaching_quality
'
Then, created a supposed data using the following lines of
codes:
# Simulate data (for the sake of demonstration)
set.seed(123)
n <- 200
peer_support <- rnorm(n, mean = 5, sd = 2)
teaching_quality <- rnorm(n, mean = 6, sd = 1.5)
engagement <- 0.5 * peer_support + rnorm(n, mean = 3, sd
= 1)
achievement <- 0.6 * teaching_quality + 0.3 *
peer_support + 0.4 * engagement + rnorm(n)
data <- data.frame(peer_support, teaching_quality,
engagement, achievement)
Then, I fit the SEM model to the data:
# Fit the model
fit <- sem(model, data = data)
# Get a summary of the model
summary(fit, fit.measures =
TRUE,
standardized = TRUE)
Then, the SEM model is visualized using the following lines
of codes:
# Plot the SEM model
semPaths(fit, what = "std", layout =
"tree", edge.label.cex = 1.2,
nCharNodes =
0, color = list(lat = "blue", man = "green"),
sizeMan = 6,
sizeLat = 8)
Source:
ChatGPT