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 the essential libraries, and
defined the SEM model using the following lines of codes:
# Load libraries
library(lavaan)
library(semPlot)
# Define the SEM model
model <- '
# Direct effect of
teacher experience on instructional methods
InstructionalMethods
~ a * TeacherExperience
# Direct effect of
instructional methods on student performance
StudentPerformance ~
b * InstructionalMethods
# Direct effect of
teacher experience on student performance
StudentPerformance ~
c * TeacherExperience
# Moderation:
Classroom environment moderates the effect of instructional methods on student
performance
StudentPerformance ~
d * Interaction
# Define indirect
(mediation) effect
indirect := a * b
# Define total
effect (direct + indirect effects)
total := c + (a * b)
'
Then, a supposed data is generated using the following lines
of codes:
# Generate sample data (if real data is not available)
set.seed(123)
n <- 300
data <- data.frame(
TeacherExperience =
rnorm(n, mean = 10, sd = 5),
ClassroomEnvironment
= rnorm(n, mean = 3, sd = 1),
InstructionalMethods
= rnorm(n, mean = 0, sd = 1),
StudentPerformance =
rnorm(n, mean = 75, sd = 10)
)
Then a relationship is created and interaction terms are
established, as follows:
# Create relationships and interaction term
data$InstructionalMethods <- 0.5 * data$TeacherExperience
+ rnorm(n)
data$StudentPerformance <- 0.3 * data$TeacherExperience +
0.6 * data$InstructionalMethods +
0.4 * data$InstructionalMethods * data$ClassroomEnvironment +
rnorm(n)
data$Interaction <- data$InstructionalMethods *
data$ClassroomEnvironment
Then we fit the model and visualized the SEM model using the
following lines of codes:
# Fit the model
fit <- sem(model, data = data)
summary(fit, standardized = TRUE, fit.measures = TRUE)
# Visualize the SEM model
semPaths(fit,
whatLabels =
"std",
layout =
"tree",
edge.color =
"blue",
sizeMan = 6,
sizeLat = 8,
fade = FALSE)
Source:
ChatGPT