# HSCI 410 Lesson 2, Activity 2.3: describe the course data and check the scales
# Run-along script for the narrated walkthrough. It reads the course data
# directly from the course website, 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 cleaned data, order the categories and load the packages
phaa <- read.csv("https://heal-learn.ca/r-activities/data/phaa_survey_clean.csv")   # course data, read from the website
phaa$smoker <- factor(phaa$smoker, levels = c("No", "Yes"))
phaa$income <- factor(phaa$income, levels = c("<25k", "25-50k", "50-75k", "75-100k", ">100k"))
library(psych)      # describe(), alpha() and fa.parallel()
library(tableone)   # CreateTableOne() for Table 1

# 2. Centre, spread and shape
summary(phaa$age)
describe(phaa[, c("age", "bmi", "systolic_bp", "phys_act_min")])
table(phaa$income, useNA = "ifany")     # ordered categories

# 3. A cross-tabulation and an odds ratio from a 2 x 2 table
round(prop.table(table(phaa$gender, phaa$smoker), margin = 1) * 100, 1)
tab <- table(Smoker = phaa$smoker, Hypertension = phaa$hypertension)
tab
(tab["Yes", "Yes"] / tab["Yes", "No"]) / (tab["No", "Yes"] / tab["No", "No"])

# 4. Four standard plots
par(mfrow = c(2, 2))
hist(phaa$systolic_bp, main = "Systolic BP", xlab = "mmHg")
boxplot(systolic_bp ~ smoker, data = phaa, ylab = "Systolic BP (mmHg)")
barplot(table(phaa$gender), main = "Gender")
plot(phaa$age, phaa$systolic_bp, xlab = "Age (years)", ylab = "Systolic BP (mmHg)")
par(mfrow = c(1, 1))

# 5. Table 1, stratified by smoking status
vars <- c("age", "gender", "bmi", "systolic_bp", "phys_act_min", "income")
t1 <- CreateTableOne(vars = vars, strata = "smoker", data = phaa, test = FALSE)
print(t1, smd = TRUE, missing = TRUE)

# 6. Internal consistency and factor structure of the scale items
dep_items <- phaa[, paste0("dep", 1:7)]      # dep1 to dep7
anx_items <- phaa[, paste0("anx", 1:5)]      # anx1 to anx5
dep_alpha <- alpha(dep_items)
round(dep_alpha$total$raw_alpha, 3)          # alpha, depression items
round(cbind(dep_alpha$alpha.drop["raw_alpha"], dep_alpha$item.stats["r.drop"]), 3)
round(alpha(anx_items)$total$raw_alpha, 3)   # alpha, anxiety items
fa.parallel(dep_items, fa = "fa")            # how many factors?
factanal(na.omit(dep_items), factors = 1)
combined <- na.omit(cbind(dep_items, anx_items))   # complete rows only
factanal(combined, factors = 2, rotation = "varimax")

# 7. Build the scale scores (at most one item missing)
n_dep <- rowSums(!is.na(dep_items))          # items answered by each person
phaa$dep_score <- ifelse(n_dep >= 6, rowMeans(dep_items, na.rm = TRUE) * 7, NA)
n_anx <- rowSums(!is.na(anx_items))
phaa$anx_score <- ifelse(n_anx >= 4, rowMeans(anx_items, na.rm = TRUE) * 5, NA)
summary(phaa$dep_score)

# 8. Is systolic BP close to normal?
qqnorm(phaa$systolic_bp); qqline(phaa$systolic_bp)
shapiro.test(phaa$systolic_bp)
