I am trying to write a function that would generate a list of contingency tables from an imported data.frame (tibble). I could use a for loop to do so; however, because of the number of rows within the file, I would rather use the apply family.
library(dplyr)
set.seed(01142022)
df <- tibble('MLST' = sample(1000:9999, 5, replace = F),
'2018(n)' = sample(1:25, 5, replace = T),
'2019(n)' = sample(1:25, 5, replace = T))
df <- rbind(df, c('Total', colSums(df[, 2:3])))
df %<>%
mutate(across(.cols = MLST, as.factor)) %>%
mutate(across(.cols = c(`2018(n)`, `2019(n)`), as.numeric))
# Contigency Table
C1 <- matrix(
data = c(df[1,2],
df[nrow(df), 2] - df[1,2],
df[1,3],
df[nrow(df), 3] - df[1,3]),
nrow = 2,
ncol = 2,
dimnames = list(c("MLST", "Non-Typed"), c("2018", "2019")))
The above code provides the reprex df of what the imported file would look like, with counts for each MLST type and a row totaling those counts. C1 is an example of how I would like each contingency table to appear for each MLST type.
Any suggestions on how to write a function that would generate a list of contingency tables for each MLST type that I could then use within one of the apply functions?