# HSCI 410 Lesson 8, Activity 8.1: load the CSCS data and keep the same people
# 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 2021 wave
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
dim(data)                                  # people (rows) and variables (columns)

# 2. Copy the four variables into a small data frame
# support:    social support (MSPSS), 1 to 7, higher = more support
# loneliness: UCLA 3-item Loneliness Scale, 3 to 9, higher = lonelier
# depression: PHQ-2 depressive symptoms, 0 to 6, higher = more symptoms
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)
summary(med_data)

# 3. Each model drops its own missing rows, so keep the same people
nobs(lm(depression ~ support, data = med_data))   # people in a total-effect model
nobs(lm(loneliness ~ support, data = med_data))   # people in a mediator model
med_data <- na.omit(med_data)              # keep people with no missing values
nrow(med_data)                             # people in every model of the lesson

# 4. How the three scores relate
round(cor(med_data[, c("support", "loneliness", "depression")]), 2)
