## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "",
  echo = FALSE, 
  fig.height = 6, 
  fig.width = 9, 
  out.width = "100%"
)

## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
library(Horsekicks)
library(dplyr)
library(tidyr)
library(ggplot2)
theme_set(theme_bw() + theme(plot.title = element_text(hjust = 0.5),
                             strip.background = element_rect(fill = "antiquewhite")))

## -----------------------------------------------------------------------------
kable(head(hkdeaths), align = "r")

## ----echo = TRUE--------------------------------------------------------------
hazards <- hkdeaths |> 
  group_by(year) |> 
  summarise(horse_kicks = sum(kick),
            falls       = sum(fall),
            drownings   = sum(drown), .groups = "drop") 
hazards_long <- hazards |> 
  pivot_longer(cols = c(horse_kicks, falls, drownings), 
               names_to = "cause", values_to = "deaths")
ggplot(hazards_long) + aes(x = year, y = deaths, colour = cause) +
  geom_line(linewidth = 1.5) +
  scale_colour_viridis_d() + 
  labs(title = "Annual Deaths from three Causes", x = "Year", y = "Deaths")

## ----echo=TRUE----------------------------------------------------------------
drown_1 <- glm(drownings ~ I(year - 1891), data = hazards, family = poisson(link = log))
exp(coef(drown_1)) |> rbind() |> as.data.frame(check.names = FALSE) |> kable(digits = 2)

## -----------------------------------------------------------------------------
b <- exp(coef(drown_1))

## ----echo=TRUE----------------------------------------------------------------
ggplot(hkdeaths) + aes(x = year, y = drown) + 
  geom_line(colour = "#21908CFF", linewidth=1.0) + facet_wrap(~ corps)  +
  geom_smooth(method = "glm", formula = y ~ I(x-1891), method.args = list(family = poisson),
              linewidth = 1.0, colour = "#440154FF", se = FALSE) + 
  labs(x = "Year", y = "Deaths", title = "Annual Drowning Deaths per Corps")


## ----eval=FALSE---------------------------------------------------------------
# # ggplot(hkdeaths) + aes(x = year, y = drown) +
# #   geom_line(colour = "#DF536B", linewidth=1.0) + facet_wrap(~ corps)  +
# #   geom_smooth(method = "glm", formula = y ~ I(x-1891), method.args = list(family = poisson),
# #               linewidth = 2, colour = "#2297E6") + labs(y = "Deaths by drowning")

