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 essential libraries, and defined
the SEM model, using the following lines of codes:
# Load the libraries
library(lavaan)
library(semPlot)
# Define the SEM model
model <- '
# Direct effects
Housing_Demand ~
Economic_Conditions
Property_Prices ~
Housing_Demand
# Moderation
(interaction term between Housing Demand and Interest Rates)
Property_Prices ~
Housing_Demand * Interest_Rates
'
Then develop a supposed dataset using the following:
# Simulate data for the model
set.seed(123) # For reproducibility
N <- 300 # Sample size
Economic_Conditions <- rnorm(N, mean = 0, sd = 1)
Housing_Demand <- 0.6 * Economic_Conditions + rnorm(N,
mean = 0, sd = 1)
Interest_Rates <- runif(N, min = 2, max = 5) # Random interest rates between 2% and 5%
Property_Prices <- 0.8 * Housing_Demand + 0.4 *
Housing_Demand * Interest_Rates + rnorm(N, mean = 0, sd = 1)
# Combine data into a dataframe
data <- data.frame(Economic_Conditions, Housing_Demand,
Interest_Rates, Property_Prices)
Then I fit the SEM model using lavaan, as follows:
# Fit the SEM model
fit <- sem(model, data = data)
# Display the summary of the SEM model
summary(fit, fit.measures = TRUE, standardized = TRUE)
Eventually, the model is visualized using semPlot, as
follows:
# Plot the SEM model
semPaths(fit, "std", whatLabels = "std",
edge.label.cex = 1.2, layout = "tree",
style =
"lisrel", residuals = FALSE, intercepts = FALSE)
Source:
ChatGPT