Friday, October 18, 2024

Day 3: 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 lavaan and semPlot packages are loaded and a SEM model is defined using the following lines of codes:

 

# Load the packages

library(lavaan)

library(semPlot)

 

# Define the SEM model

model <- '

  # Direct effect of Perceived Product Quality on Brand Loyalty

  BL ~ c1*PPQ

 

  # Indirect effect via Customer Satisfaction

  CS ~ a*PPQ

  BL ~ b*CS

 

  # Mediation effect (indirect path)

  indirect := a * b

 

  # Total effect

  total := c1 + (a * b)

'

 

In the above code, a path model is defined representing the direct and indirect effects. Direct path is shown by the effect of Perceived Product Quality (PPQ) on Brand Loyalty (BL) and indirect path is shown by the effect of Perceived Product Quality (PPQ) on Customer Satisfaction (CS) on Brand Loyalty (BL).

Then a supposed data is generated using the following lines of codes:

 

# Simulate some data for 300 participants

set.seed(123)

data <- data.frame(

  PPQ = rnorm(300, mean = 5, sd = 1.5),  # Perceived Product Quality

  CS = rnorm(300, mean = 5, sd = 1.5),   # Customer Satisfaction

  BL = rnorm(300, mean = 5, sd = 1.5)    # Brand Loyalty

)

 

# Adding some correlation between variables to make the SEM model meaningful

data$CS <- 0.5 * data$PPQ + rnorm(300, 0, 0.5)   # Satisfaction depends on Product Quality

data$BL <- 0.3 * data$PPQ + 0.4 * data$CS + rnorm(300, 0, 0.5)  # Loyalty depends on both PPQ and CS

 

Then the SEM model is fit to the data using lavaan package using the following lines of codes:

 

# Fit the model to the simulated data

fit <- sem(model, data = data)

 

# Get the summary of the model fit

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

 

Then the model is visualized using the semPlot

 

# Plot the SEM model

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

         edge.color = "black", nCharNodes = 5, style = "ram",

         residuals = FALSE, exoCov = FALSE)

 

Source:
ChatGPT


No comments: