# HSCI 410 Lesson 4, Activity 4.1: logistic regression as a generalized linear model
# 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 count the events
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$hypertension <- factor(phaa$hypertension, levels = c("No", "Yes"))   # "Yes" = event
table(phaa$hypertension)     # how many people had the event?

# 2. Why not a straight line? A linear model for a 0/1 outcome
lin01 <- lm(as.numeric(hypertension == "Yes") ~ age + smoker, data = phaa)
range(fitted(lin01))         # the "probabilities" a straight line predicts
plot(lin01, which = 1)       # Residuals vs Fitted for a 0/1 outcome

# 3. The GLM: binomial distribution, logit link, linear predictor
logit <- glm(hypertension ~ age + smoker, data = phaa, family = binomial)
summary(logit)
exp(cbind(OR = coef(logit), confint(logit)))   # odds ratios with 95% CIs

# 4. The crude odds ratio for smoking, for comparison
crude <- glm(hypertension ~ smoker, data = phaa, family = binomial)
exp(cbind(OR = coef(crude), confint(crude)))
