# HSCI 410 Lesson 7, Activity 7.2: Cronbach's alpha, omega and a missed reversal
# 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 code the six loneliness items
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
dj <- data[, paste0("LONELY_dejong_emotional_social_loneliness_scale_",
                    c("emptiness", "miss", "rejected", "rely", "trust", "close"))]
names(dj) <- c("emptiness", "miss", "rejected", "rely", "trust", "close")
answers <- c("No", "More or less", "Yes")  # coded 1, 2 and 3; anything else NA
stored <- na.omit(data.frame(lapply(dj, match, table = answers)))
soc <- c("rely", "trust", "close")         # the positively worded items
items <- stored
items[, soc] <- 4 - stored[, soc]          # reverse: 1 becomes 3, 3 becomes 1
nrow(items)                                # people who answered all six items

# 2. Cronbach's alpha for each subscale
library(psych)                             # alpha() and fa()
social_items    <- items[, soc]
emotional_items <- items[, c("emptiness", "miss", "rejected")]
alpha(social_items)
a_emo <- alpha(emotional_items)
round(a_emo$total, 2)                      # overall alpha only
round(a_emo$alpha.drop[, 1:2], 2)          # alpha if each item is dropped
round(a_emo$item.stats[, "r.drop", drop = FALSE], 2)   # corrected item-total r

# 3. McDonald's omega from a one-factor model of each subscale
f_soc  <- fa(social_items, nfactors = 1)   # one-factor model
lambda <- f_soc$loadings[, 1]              # the three loadings
round(lambda, 2)
sum(lambda)^2 / (sum(lambda)^2 + sum(f_soc$uniquenesses))   # omega
f_emo  <- fa(emotional_items, nfactors = 1)
lambda <- f_emo$loadings[, 1]
round(lambda, 2)
sum(lambda)^2 / (sum(lambda)^2 + sum(f_emo$uniquenesses))

# 4. An index: the Steptoe social isolation index (1 = isolated on that part)
iso <- data[, paste0("LONELY_steptoe_isolation_index_",
                     c("unmarried", "clubs", "friends", "kids", "other_fam"), "_num")]
names(iso) <- c("unmarried", "clubs", "friends", "children", "family")
iso <- na.omit(iso)
round(cor(iso), 2)
round(alpha(iso)$total[, 1:2], 2)          # shown only to explain why it is not reported

# 5. Alpha for all six items, correctly reverse-coded
round(alpha(items)$total[, 1:2], 2)
