Let's take the following dataframe as an example:
df <- data.frame(state = c('up', 'up', 'up', 'down', 'down', 'up', 'down', 'down'), type = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'))
To count how many times each of the possible combinations of A/B and up/down occur I would do as follows:
a1 <- nrow(subset(subset(df, state == 'up'), type == 'A'))
a2 <- nrow(subset(subset(df, state == 'down'), type == 'A'))
a3 <- nrow(subset(subset(df, state == 'up'), type == 'B'))
a4 <- nrow(subset(subset(df, state == 'down'), type == 'B'))
And to show that in a Rmarkdown table I would do as follows:
| State/type | A | B |
|:--------------:|:------:|:------:|
| Up | `r a1` | `r a3` |
| Down | `r a2` | `r a4` |
My question is: is there a better way to do this? This approach becomes very tedious when you have many factor combinations and scales poorly.