Tuesday, October 22, 2024

Day 7: 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 essential libraries, including lavaan and semPlot, and then defined the SEM model, as follows:

 

library(lavaan)

library(semPlot)

 

# Define the SEM model

model <- '

  # Direct effects

  Z ~ b1*X + b2*Y

 

  # Indirect effects (X affects Z through Y)

  Y ~ a1*X

 

  # Calculate the indirect effect

  indirect := a1 * b2

 

  # Total effect of X on Z

  total := b1 + (a1 * b2)

'

 

These aspects can be explained as follows:

·        Z ~ b1X + b2Y: Disease risk (Z) is predicted by genetic predisposition (X) and environmental factors (Y).

·        Y ~ a1*X: Environmental factors (Y) are predicted by genetic predisposition (X).

·        indirect := a1 * b2: Defines the indirect effect of genetic predisposition (X) on disease risk (Z) through environmental factors (Y).

·        total := b1 + (a1 * b2): Defines the total effect of genetic predisposition (X) on disease risk (Z), which includes both the direct and indirect effects.

Then the supposed data is generated as follows:

# Set seed for reproducibility

set.seed(123)

 

# Simulate data with 300 observations

n <- 300

X <- rnorm(n, mean = 0, sd = 1)  # Genetic predisposition

Y <- 0.6 * X + rnorm(n, mean = 0, sd = 1)  # Environmental factors influenced by X

Z <- 0.5 * X + 0.7 * Y + rnorm(n, mean = 0, sd = 1)  # Disease risk influenced by X and Y

 

# Combine into a data frame

data <- data.frame(X = X, Y = Y, Z = Z)

 

Then, the SEM model is fitted using the following codes:

 

# Fit the SEM model to the data

fit <- sem(model, data = data)

 

# Summarize the model fit

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

 

The model is visualized using the following lines of codes:

 

# Visualize the SEM model using semPlot

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

         nCharNodes = 6, edge.color = "blue", style = "lisrel")

Source:
ChatGPT


 


No comments: