## -----------------------------------------------------------------------------
#| echo: false
#| message: false
#| warning: false
library(tidyverse)
library(flextable)


## -----------------------------------------------------------------------------
lister <- read.delim('https://github.com/IowaBiostat/data-sets/raw/main/lister/lister.txt')

tab <- with(lister, xtabs(~ Group + Outcome))
tbl <- tab[2:1, 2:1]

chisq.test(tbl, correct = FALSE)

fisher.test(tbl)


## -----------------------------------------------------------------------------
#| eval: false
# cirr$dead <- ifelse(cirr$Status == 2, 1, 0)


## -----------------------------------------------------------------------------
cirr <- read.delim('https://raw.githubusercontent.com/IowaBiostat/data-sets/main/cirrhosis/cirrhosis.txt')

cirr$dead <- ifelse(cirr$Status == 2, 1, 0)

tbl <- with(cirr, xtabs(~ Group + dead))
chisq.test(tbl, correct = FALSE)


## -----------------------------------------------------------------------------
tbl2 <- rbind(
  c(93, 65),
  c(94, 60)
)

chisq.test(tbl2, correct = FALSE)


## -----------------------------------------------------------------------------
#| echo: false
tbl


## -----------------------------------------------------------------------------
#| echo: false
(expect <- chisq.test(tbl, correct=FALSE)$expected)


## -----------------------------------------------------------------------------
#| echo: false
term <- rep(NA, 4)
for (i in 1:length(tbl)){
  term[i] <- (tbl[i] - expect[i])^2 / expect[i]
}
round(term, 4)


## -----------------------------------------------------------------------------
#| echo: false
sum(term)


## -----------------------------------------------------------------------------
fisher.test(tbl)


## -----------------------------------------------------------------------------
#| echo: false
matrix(
  c("a","b","c","d"), nrow =2
) |> 
  as.data.frame() |> 
  rename("diseaseYes" = V1, 
         "diseaseNo" = V2) |> 
  flextable() 

