# HSCI 410 Lesson 8, Activity 8.3: mediation, from three regressions to mediate()
# Run-along script for the narrated walkthrough. It reads the survey 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 variables for the mediation model
github_url <- "https://raw.githubusercontent.com/jorgeandr3s/heal/main/cscs/public_data/CSCS2025_full_cleaned_deidentified_data_and_metadata.RData"
load(url(github_url))                      # survey data, read from the web
data <- data[data$SURVEY_collection_year == 2021, ]   # the 2021 wave
med_data <- data.frame(
  support    = data$PSYCH_zimet_multidimensional_social_support_scale_score,
  loneliness = data$LONELY_ucla_loneliness_scale_score,
  depression = data$WELLNESS_phq_score,
  age        = data$DEMO_age)
med_data <- na.omit(med_data)              # the same people in every model
nrow(med_data)

# 2. Three regressions give the four paths
model_total <- lm(depression ~ support, data = med_data)           # path c
round(cbind(estimate = coef(model_total), confint(model_total)), 3)
model_a <- lm(loneliness ~ support, data = med_data)               # path a
round(cbind(estimate = coef(model_a), confint(model_a)), 3)
model_b <- lm(depression ~ support + loneliness, data = med_data)  # b and c'
round(cbind(estimate = coef(model_b), confint(model_b)), 3)

# 3. The indirect effect, calculated two ways
a        <- coef(model_a)["support"]
b        <- coef(model_b)["loneliness"]
c_total  <- coef(model_total)["support"]
c_direct <- coef(model_b)["support"]
a * b                  # product of coefficients
c_total - c_direct     # difference method

# 4. Bootstrap confidence intervals with mediate()
library(mediation)     # install.packages("mediation") once, if needed
set.seed(2021)         # makes the bootstrap repeatable
med_result <- mediate(model_a, model_b, treat = "support",
                      mediator = "loneliness", boot = TRUE, sims = 1000)
summary(med_result)
plot(med_result, xlim = c(-0.7, 0))   # the three effects with 95% CIs
