I am trying to create one table that summarizes several categorical variables (using frequencies and proportions) of another variable. I would like to do this using the dplyr package.
These previous discussions partially change: Relative frequencies / proportions with dplyr and Calculate relative frequency for a specific group .
Using the mtcars dataset, it will look as if I just wanted to see the proportion of gear on am :
mtcars %>% group_by(am, gear) %>% summarise (n = n()) %>% mutate(freq = n / sum(n))
However, in fact, I want to look not only gears on am , but also carb on am and cyl on am , separately, in the same table. If I fix the code, follow these steps:
mtcars %>% group_by (am, gear, carb, cyl) %>% summarise (n = n()) %>% mutate(freq = n / sum(n))
I get frequencies for each combination of am , gear , carb and cyl . This is not what I want. Is there a way to do this with dplyr?
EDIT
Also, it would be an added bonus if someone knew about the way to create the table I want, but with am categories as columns (as in the classic 2x2 table format). Here is an example of what I'm talking about. This is from one of my previous publications. I want to create this table in R so that I can output it directly to a text document using RMarkdown:

source share