# HSCI 410 Lesson 4, Activity 4.2: ordinal logistic regression for self-rated health
# 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 data and check the categories
library(MASS)    # polr() fits the ordinal logistic model
library(brant)   # brant() checks it; if missing, run install.packages("brant") once
phaa <- read.csv("https://heal-learn.ca/r-activities/data/phaa_outcomes.csv")   # course data, read from the website
phaa <- na.omit(phaa)                   # keep the 795 people with no missing values
phaa$smoker <- factor(phaa$smoker, levels = c("No", "Yes"))   # "No" = reference
phaa$self_rated_health <- factor(phaa$self_rated_health,
  levels = c("Poor", "Fair", "Good", "Very good", "Excellent"), ordered = TRUE)
table(phaa$smoker, phaa$self_rated_health)   # people in each category, by smoking

# 2. Fit the ordinal (proportional-odds) model
ord <- polr(self_rated_health ~ age + smoker, data = phaa, Hess = TRUE)
summary(ord)

# 3. Odds ratios with 95% CIs, per year and per ten years of age
exp(cbind(OR = coef(ord), confint(ord)))   # odds ratios with 95% CIs
exp(10 * coef(ord)["age"])                 # odds ratio for ten years of age
exp(10 * confint(ord)["age", ])            # and its 95% CI

# 4. Check the proportional-odds assumption
brant(ord)                                 # H0: the assumption holds
# odds ratios from a separate logistic regression at each split ("k or better")
split_or <- sapply(c("Fair", "Good", "Very good", "Excellent"), function(k)
  coef(glm(self_rated_health >= k ~ age + smoker, data = phaa, family = binomial))[-1])
round(exp(split_or), 3)
