Saturday, October 26, 2024

Day 11: 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, I loaded lavaan and semPlot, and defined the SEM model, as follows:

# Load the packages

library(lavaan)

library(semPlot)

 

# Define the SEM model

model <- '

  # Direct effect

  productivity ~ management + job_satisfaction + workplace

 

  # Indirect effect

  job_satisfaction ~ management

'

 

Then, a supposed data was developed, as follows:

# Simulate a dataset with the relevant variables

set.seed(123)  # For reproducibility

 

n <- 200  # Number of observations

 

# Simulate random variables for the model

management <- rnorm(n, mean = 5, sd = 2)  # Management style

job_satisfaction <- 0.5 * management + rnorm(n, mean = 0, sd = 1)  # Job satisfaction

workplace <- rnorm(n, mean = 4, sd = 1.5)  # Workplace environment

productivity <- 0.3 * management + 0.4 * job_satisfaction + 0.5 * workplace + rnorm(n, mean = 0, sd = 1)  # Productivity

 

# Combine into a data frame

data <- data.frame(management, job_satisfaction, workplace, productivity)

 

# Inspect the data

head(data)

 

Then, lavaan was used to fit the SEM model, as follows:

 

# Fit the model

fit <- sem(model, data = data)

 

# Display the summary of the SEM results

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

 

Eventually, the model is visualized using the semPlot package, as follows:

# Visualize the SEM model

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

         style = "ram", nCharNodes = 0, curvePivot = TRUE)

 

Source:

ChatGPT


No comments: