title: Using dplyr to create summary proportion table with several categorical/factor variables
body: <p>I am trying to create one table that summarizes several categorical variables (using frequencies and proportions) by another variable. I would like to do this using the dplyr package.</p>
  
  <p>These previous Stack Overflow discussions have partially what I am looking for: 
  <a href="https://stackoverflow.com/questions/24576515/relative-frequencies-proportions-with-dplyr">Relative frequencies / proportions with dplyr</a> and <a href="https://stackoverflow.com/questions/27676128/calculate-relative-frequency-for-a-certain-group?rq=1">Calculate relative frequency for a certain group</a>.</p>
  
  <p>Using the mtcars dataset, this is what the output would look like if I just wanted to look at the proportion of <code>gear</code> by <code>am</code> category:</p>
  
  <pre><code>    mtcars %&gt;%
      group_by(am, gear) %&gt;%
      summarise (n = n()) %&gt;%
      mutate(freq = n / sum(n))
  
      #   am gear  n      freq
      # 1  0    3 15 0.7894737
      # 2  0    4  4 0.2105263
      # 3  1    4  8 0.6153846
      # 4  1    5  5 0.3846154
  </code></pre>
  
  <p>However, I actually want to look at not only the <code>gears</code> by <code>am</code>, but also <code>carb</code> by <code>am</code> and <code>cyl</code> by <code>am</code>, separately, in the same table. If I amend the code to:</p>
  
  <pre><code>    mtcars %&gt;%
      group_by (am, gear, carb, cyl) %&gt;%
      summarise (n = n()) %&gt;%
      mutate(freq = n / sum(n))
  </code></pre>
  
  <p>I get the frequencies for each combination of <code>am</code>, <code>gear</code>, <code>carb</code>, and <code>cyl</code>. Which is not what I want. Is there any way to do this with dplyr?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Also, it would be an added bonus if anyone knew of a way to produce the table I want, but with the categories of <code>am</code> as the columns (as in a classic 2x2 table format). Here is an example of what i'm referring to. It is from one of my previous publications. I want to produce this table in R, so that I can output it directly to a word document using RMarkdown:</p>
  
  <p><a href="https://i.stack.imgur.com/1TM8D.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1TM8D.png" alt="enter image description here"></a></p>