# HSCI 410 Lesson 8, Activity 8.4: path models and a first structural equation model
# Run-along script for the narrated walkthrough. It reads the CSCS data
# directly from the web, so there is nothing to set up: open it
# in RStudio and run each part with Ctrl+Enter when the narration asks.

# 1. Read the CSCS data and keep the people with all four scores
library(lavaan)              # install.packages("lavaan") once, if needed
load(url("https://raw.githubusercontent.com/jorgeandr3s/heal/main/cscs/public_data/CSCS2025_full_cleaned_deidentified_data_and_metadata.RData"))   # CSCS data, read from the web
data <- data[data$SURVEY_collection_year == 2021, ]   # the 2021 wave
path_data <- data.frame(
  support    = data$PSYCH_zimet_multidimensional_social_support_scale_score,
  loneliness = data$LONELY_ucla_loneliness_scale_score,   # UCLA, 3 to 9
  depression = data$WELLNESS_phq_score,                   # PHQ-2, 0 to 6
  anxiety    = data$WELLNESS_gad_score)                   # GAD-2, 0 to 6
path_data <- na.omit(path_data)   # people with all four scores
nrow(path_data)

# 2. The simple mediation model, written in lavaan
model_med <- '
  loneliness ~ a * support
  depression ~ b * loneliness + c * support
  indirect := a * b
  total    := c + a * b
'
fit_med <- sem(model_med, data = path_data)
summary(fit_med)

# 3. Model 1: no direct paths from support to the two outcomes
model_full <- '
  loneliness ~ support
  depression ~ loneliness
  anxiety    ~ loneliness
  depression ~~ anxiety
'
fit_full <- sem(model_full, data = path_data)
fitMeasures(fit_full, c("chisq", "df", "pvalue", "cfi", "tli", "rmsea", "srmr"))

# 4. Model 2: adds a direct path to each outcome, then compare
model_partial <- '
  loneliness ~ a * support
  depression ~ b1 * loneliness + c1 * support
  anxiety    ~ b2 * loneliness + c2 * support
  depression ~~ anxiety
  indirect_dep := a * b1
  indirect_anx := a * b2
'
fit_partial <- sem(model_partial, data = path_data)
fitMeasures(fit_partial, c("chisq", "df", "cfi", "rmsea", "srmr"))
anova(fit_full, fit_partial)   # chi-square difference test, AIC and BIC

# 5. Model 2 with 1,000 bootstrap samples (about two minutes)
set.seed(2021)
fit_boot <- sem(model_partial, data = path_data,
                se = "bootstrap", bootstrap = 1000)
est <- parameterEstimates(fit_boot, boot.ci.type = "perc")
est[est$op %in% c("~", ":="), c("lhs", "op", "rhs", "est", "ci.lower", "ci.upper")]

# 6. Standardized estimates and R-squared
std <- standardizedSolution(fit_boot)
std[std$lhs != std$rhs, c("lhs", "op", "rhs", "est.std")]   # paths, covariance, indirect
lavInspect(fit_boot, "rsquare")   # variance explained

# 7. A structural equation model with a latent loneliness factor
sem_data <- data.frame(
  companionship = data$LONELY_ucla_loneliness_scale_companionship_num,
  left_out      = data$LONELY_ucla_loneliness_scale_left_out_num,
  isolated      = data$LONELY_ucla_loneliness_scale_isolated_num,
  support       = data$PSYCH_zimet_multidimensional_social_support_scale_score,
  depression    = data$WELLNESS_phq_score)
sem_data <- na.omit(sem_data)   # people with all five scores
nrow(sem_data)
model_sem <- '
  Lonely =~ companionship + left_out + isolated
  Lonely     ~ a * support
  depression ~ b * Lonely + c * support
  indirect := a * b
'
fit_sem <- sem(model_sem, data = sem_data)
fitMeasures(fit_sem, c("chisq", "df", "cfi", "rmsea", "srmr"))
