You can use xtabs() to make a multidimensional tabulation, and then flatten it for display using ftable().
library(tidyverse)
df <- tribble(
~Gender, ~AgeBand, ~TypeOfIllness,
"Male", "0 - 64", "Illness One",
"Male", "0 - 64", "Illness One",
"Male", "0 - 64", "Illness Two",
"Male", "65+", "Illness Three",
"Female", "65+", "Illness Three",
"Male", "0 - 64", "Illness Four",
"Female", "65+", "Illness Four",
"Female", "65+", "Illness Five",
"Female", "0 - 64", "Illness Five",
"Female", "65+", "Illness Two"
)
df <- df %>% mutate(
Gender = factor(Gender),
AgeBand = factor(AgeBand, levels = c("0 - 64", "65+")),
TypeOfIllness = factor(
TypeOfIllness,
levels = c(
"Illness One", "Illness Two",
"Illness Three", "Illness Four", "Illness Five"
)
)
)
xtabs(~ TypeOfIllness + AgeBand + Gender, data = df) %>%
addmargins(c(1, 3)) %>%
ftable(col.vars = c("Gender", "AgeBand"))
#> Gender Female Male Sum
#> AgeBand 0 - 64 65+ 0 - 64 65+ 0 - 64 65+
#> TypeOfIllness
#> Illness One 0 0 2 0 2 0
#> Illness Two 0 1 1 0 1 1
#> Illness Three 0 1 0 1 0 2
#> Illness Four 0 1 1 0 1 1
#> Illness Five 1 1 0 0 1 1
#> Sum 1 4 4 1 5 5
Created on 2018-05-22 by the reprex package (v0.2.0).
The only difficult part is getting the Total column exactly like the one in your example. How important is that to what you're doing?
I'm not sure I follow this part. What sort of file format are you trying to save as?