# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .r
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: R 4.1.2
#     language: R
#     name: ir41
# ---

# # Water fluoridation and Dental Caries
#
# **Date:** 2021-12-01
#
# **Reference:** M249, Book 1, Part 2

suppressPackageStartupMessages(library(tidyverse))
library(R249)
library(DescTools)

# ## Summary

# ## Get the data

(dat <- as_tibble(read.csv(file = "..\\..\\data\\dentalcaries.csv")))

# ## Prepare the data
#
# Cast the `exposure`, `outcome`, `level` columns to factors.

labexp <- c("not fluoridated", "fluoridated")
labout <- c("caries", "no caries")
lablev <- c("age 8 years", "age 9 years", "age 10 years", "age 11-12 years")
(sorteddat <- dat %>%
    mutate(exposure = factor(dat$exposure, labexp)) %>%
    mutate(outcome = factor(dat$outcome, labout)) %>%
    mutate(level = factor(dat$level, lablev)) %>%
    arrange(level, exposure, outcome))

# Filter the tibble on each specific `level`, pull the `count` column as a vector and initilise a matrix.
# Append this new matrix to an array.

age8 <- filter(sorteddat, level == "age 8 years") %>%
    pull(count) %>%
    matrix(nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(labexp, labout))
age9 <- filter(sorteddat, level == "age 9 years") %>%
    pull(count) %>%
    matrix(nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(labexp, labout))
age10 <- filter(sorteddat, level == "age 10 years") %>%
    pull(count) %>%
    matrix(nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(labexp, labout))
age11_12 <- filter(sorteddat, level == "age 11-12 years") %>%
    pull(count) %>%
    matrix(nrow = 2, ncol = 2, byrow = TRUE, dimnames = list(labexp, labout))
datarr <- array(
    c(age8, age9, age10, age11_12),
    dim = c(2, 2, 4),
    dimnames = list(labexp, labout, lablev)
)
print(datarr)

# ## Stratum-specific odds ratios
#
# Calculate the stratum-specific odds ratio.
#
# Note, we do not calculate the stratum-specific odds ratio for level age 9 years, given the presence of the 0 count.

# age 8 years
oddsratio(datarr[, , 1])

# age 10 years
oddsratio(datarr[, , 3])

# age 11-12 years
oddsratio(datarr[, , 4])

# ## Crude odds ratio

oddsratio_crude(datarr)

# ## Tarone's test for homogeneity

BreslowDayTest(datarr, correct = TRUE)

# ## Mantel-Haenszel odds ratio and chi-squared test

mantelhaen.test(datarr)

StarcoderdataJupyterScriptsDedupFiltered