Thursday, October 17, 2024

Day 2: A challenge to learn basics of Structural Equation Modeling (SEM) using lavaan and semPlot packages in R

 

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, initially essential libraries, including lavaan and semPlot are loaded, and model is defined. For instance, social status affects education level, education level affects political participation, and social status affects political participation. Following lines of codes can be used:

library(lavaan)

library(semPlot)

 

model <- '

  # Direct effect

  political_participation ~ social_status

 

  # Mediated effect

  education_level ~ social_status

  political_participation ~ education_level

'

 

For this analysis, a supposed data can be generated using the following codes:

 

set.seed(123)  # For reproducibility

n <- 300  # Number of observations

 

# Simulate the data

social_status <- rnorm(n, mean = 50, sd = 10)

education_level <- 0.6 * social_status + rnorm(n, mean = 0, sd = 5)

political_participation <- 0.4 * social_status + 0.7 * education_level + rnorm(n, mean = 0, sd = 5)

 

# Combine into a data frame

data <- data.frame(social_status, education_level, political_participation)

 

Then, the model is fit in lavaan, using the following lines of codes:

 

fit <- sem(model, data = data)

 

# Check the summary of the model

summary(fit, fit.measures = TRUE, standardized = TRUE)

 

Then, the model is visualized using semPlot, as follows:

 

semPaths(fit, whatLabels = "std", layout = "tree", edge.label.cex = 1.2,

         residuals = TRUE, intercepts = FALSE)

 

Eventually, the results are analyzed.

Source:
ChatGPT

No comments: