# HSCI 410 Lesson 7, Activity 7.4: exploratory and confirmatory factor analysis
# 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. Load the packages, read the CSCS data and prepare the six loneliness items
# install.packages(c("psych", "GPArotation", "lavaan"))   # run once, if not yet installed
library(psych); library(GPArotation); library(lavaan)
load(url("https://raw.githubusercontent.com/jorgeandr3s/heal/main/cscs/public_data/CSCS2025_full_cleaned_deidentified_data_and_metadata.RData"))
data <- data[data$SURVEY_collection_year == 2021, ]   # the 2021 wave
item_names <- c("emptiness", "miss", "rejected", "rely", "trust", "close")
items <- data[, paste0("LONELY_dejong_emotional_social_loneliness_scale_", item_names)]
names(items) <- item_names
codes <- c("No" = 1, "More or less" = 2, "Yes" = 3)   # other answers become NA
items[] <- lapply(items, function(x) unname(codes[as.character(x)]))
items[, 4:6] <- 4 - items[, 4:6]   # reverse rely, trust, close: higher = lonelier
items <- na.omit(items)            # the people who answered all six items
nrow(items)
round(cor(items), 2)               # correlations between every pair of items

# 2. Split the sample at random: explore in one half, confirm in the other
set.seed(2021)                     # the same random split every time
efa_rows <- sample(nrow(items), size = round(nrow(items) / 2))
efa_half <- items[efa_rows, ]      # half 1: exploratory
cfa_half <- items[-efa_rows, ]     # half 2: confirmatory
c(nrow(efa_half), nrow(cfa_half))

# 3. Exploratory factor analysis in the first half
KMO(efa_half)                      # overall MSA above 0.6 is usually adequate
cortest.bartlett(cor(efa_half), n = nrow(efa_half))
fa.parallel(efa_half, fa = "fa")   # how many factors? (it also draws a plot)
efa_2 <- fa(efa_half, nfactors = 2, rotate = "oblimin")
print(efa_2$loadings, cutoff = 0.3)   # loadings below 0.3 are hidden
round(efa_2$communality, 2)        # share of each item's variance explained
round(efa_2$Phi, 2)                # correlation between the two factors

# 4. Confirmatory factor analysis in the second half ("=~": is measured by)
model_2f <- '
  emotional =~ emptiness + miss + rejected
  social    =~ rely + trust + close
'
cfa_2f <- cfa(model_2f, data = cfa_half)
summary(cfa_2f, fit.measures = TRUE, standardized = TRUE, rsquare = TRUE)
fitMeasures(cfa_2f, c("cfi", "tli", "rmsea", "srmr"))   # the four fit indices
