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 prepared
a data, using the following lines of codes:
# Load the required libraries
library(lavaan)
library(semPlot)
library(psych)
# Simulate data
set.seed(123) # For
reproducibility
n <- 300 # Number
of samples
# Latent variables
Knowledge <- rnorm(n, mean = 0, sd = 1)
Attitudes <- 0.5 * Knowledge + rnorm(n, mean = 0, sd = 1)
Behavior <- 0.7 * Knowledge + 0.4 * Attitudes + rnorm(n,
mean = 0, sd = 1)
# Observed indicators for each latent variable
Know1 <- 0.8 * Knowledge + rnorm(n, mean = 0, sd = 0.5)
Know2 <- 0.9 * Knowledge + rnorm(n, mean = 0, sd = 0.5)
Know3 <- 0.7 * Knowledge + rnorm(n, mean = 0, sd = 0.5)
Att1 <- 0.8 * Attitudes + rnorm(n, mean = 0, sd = 0.5)
Att2 <- 0.9 * Attitudes + rnorm(n, mean = 0, sd = 0.5)
Att3 <- 0.7 * Attitudes + rnorm(n, mean = 0, sd = 0.5)
Beh1 <- 0.8 * Behavior + rnorm(n, mean = 0, sd = 0.5)
Beh2 <- 0.9 * Behavior + rnorm(n, mean = 0, sd = 0.5)
Beh3 <- 0.7 * Behavior + rnorm(n, mean = 0, sd = 0.5)
# Create a data frame
data <- data.frame(Know1, Know2, Know3, Att1, Att2, Att3,
Beh1, Beh2, Beh3)
The above code shows three observed variables for each
latent factor. For example,
Knowledge: Know1, Know2, Know3
Attitudes: Att1, Att2, Att3
Behavior: Beh1, Beh2, Beh3
Then the SEM model is specified, using the following lines
of codes:
# SEM model specification
model <- '
# Measurement model
Knowledge =~ Know1 +
Know2 + Know3
Attitudes =~ Att1 +
Att2 + Att3
Behavior =~ Beh1 + Beh2 + Beh3
# Structural model
Attitudes ~
Knowledge
Behavior ~ Knowledge + Attitudes
'
The SEM model is fitted using lavaan, and visualized using
the semPaths, as follows:
# Fit the SEM model
fit <- sem(model, data = data)
# Summarize the results
summary(fit, fit.measures = TRUE, standardized = TRUE)
# Plot the SEM path diagram
semPaths(fit, "std", layout = "tree",
residuals = TRUE, nCharNodes = 7, edge.label.cex = 1.2)
Source:
ChatGPT
No comments:
Post a Comment