# HSCI 410 Lesson 4, Activity 4.3: multinomial logistic regression for usual place of care
# 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, set the reference category and check the numbers
library(nnet)                           # multinom() fits the multinomial model
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$usual_care <- relevel(factor(phaa$usual_care), ref = "Family doctor")   # reference category
table(phaa$usual_care, phaa$smoker)     # enough people in every category?

# 2. Fit the model: one comparison for each category
mn <- multinom(usual_care ~ age + smoker, data = phaa, trace = FALSE)
summary(mn)

# 3. Relative risk ratios (RRR) with 95% CIs
round(exp(coef(mn)), 2)                 # relative risk ratios
round(exp(confint(mn)), 2)              # 95% CIs, one block per comparison
round(exp(10 * coef(mn)[, "age"]), 2)   # RRRs for ten years of age

# 4. Predicted probabilities for two 30-year-olds
new_people <- data.frame(age = 30, smoker = c("No", "Yes"))   # a non-smoker and a smoker
round(predict(mn, newdata = new_people, type = "probs"), 2)
