# Keep model variables; drop any missing data
dep <- ah4[c("depressSS", "woman", "role", "income", "age", "race")]
dep <- dep[complete.cases(dep), ]
dep <- dep |> mutate(across(c(woman, race), as_factor))
# 6.7.b - compare predictions to choose model
nbdep <- glm.nb(depressSS ~ woman + poly(role, 2, raw = TRUE) + income + age + race,
data = dep)
pdep <- glm(depressSS ~ woman + poly(role, 2, raw = TRUE) + income + age + race,
family = "poisson", data = dep)
meanpred <- data.frame(k = 0:30) |>
mutate(Observed = sapply(k, function(j) mean(dep$depressSS == j)),
Poisson = sapply(k, function(j) mean(dpois(j, fitted(pdep)))),
"Neg. Binomial" = sapply(k, function(j)
mean(dnbinom(j, size = nbdep$theta, mu = fitted(nbdep))))) |>
pivot_longer(-k, names_to = "type", values_to = "pr") |>
mutate(type = factor(type, levels = c("Observed", "Poisson", "Neg. Binomial")))
ggplot(meanpred, aes(x = k, y = pr, color = type)) +
geom_line() + geom_point() +
annotate("text", x = 20, y = .15, label = 'mu == "6.09"', parse = TRUE) +
annotate("text", x = 20, y = .135, label = 'sigma^2 == "21.99"', parse = TRUE) +
scale_x_continuous(breaks = seq(0, 30, 5)) +
scale_y_continuous(breaks = seq(0, .2, .05), limits = c(0, .2)) +
labs(title = "[6.7.b] Comparison of Mean Predictions from Poisson and Negative Binomial",
x = "Number of Depressive Symptoms", y = "Pr(y = k)", color = NULL)