title: Group data hierarchically on two levels, then compute relative frequencies in R using dplyr
body: <p>I want to do something which appears simple, but I don't have a good feel for R yet, it is a maze of twisty passages, all different.</p>
  
  <p>I have a table with several variables, and I want to group on two variables ... I want a two-level hierarchical grouping, also known as a tree. This can evidently be done using the <a href="https://www.rdocumentation.org/packages/dplyr/versions/0.7.8/topics/group_by" rel="nofollow noreferrer">group_by</a> function of <a href="https://www.rdocumentation.org/packages/dplyr/versions/0.7.8" rel="nofollow noreferrer">dplyr</a>. </p>
  
  <p>And then I want to compute marginal statistics (in this case, relative frequencies) based on group counts for level 1 and level 2.</p>
  
  <p>In pictures, given this table of 18 rows:</p>
  
  <p><a href="https://i.stack.imgur.com/RBIdC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RBIdC.png" alt="table we have"></a></p>
  
  <p>I want this table of 6 rows:</p>
  
  <p><a href="https://i.stack.imgur.com/xNoHZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xNoHZ.png" alt="table we want"></a></p>
  
  <p>Is there a simple way to do this in dplyr? (I can do it in SQL, but ...)</p>
  
  <p><strong>Edited for example</strong></p>
  
  <p>For example, based on the <code>nycflights13</code> package:</p>
  
  <pre><code>library(dplyr)
  install.packages("nycflights13")
  require(nycflights13)
  data(flights) # contains information about flights, one flight per row
  ff &lt;- flights %&gt;% 
        mutate(approx_dist = floor((distance + 999)/1000)*1000) %&gt;%
        select(carrier, approx_dist) %&gt;%
        group_by(carrier, approx_dist) %&gt;% 
        summarise(n = n()) %&gt;% 
        arrange(carrier, approx_dist)
  </code></pre>
  
  <p>This creates a tbl <code>ff</code> with the number of flights for each pair of (carrier, inter-airport-distance-rounded-to-1000s):</p>
  
  <pre><code># A tibble: 33 x 3
  # Groups:   carrier [16]
     carrier approx_dist     n
     &lt;chr&gt;         &lt;dbl&gt; &lt;int&gt;
   1 9E             1000 15740
   2 9E             2000  2720
   3 AA             1000  9146
   4 AA             2000 17210
   5 AA             3000  6373
  </code></pre>
  
  <p>And now I would like to compute the relative frequencies for the "approx_dist" values in each "carrier" group, for example, I would like to get:</p>
  
  <pre><code>   carrier approx_dist     n   rel_freq
     &lt;chr&gt;         &lt;dbl&gt; &lt;int&gt; 
   1 9E             1000 15740   15740/(15740+2720)
   2 9E             2000  2720    2720/(15740+2720)
  </code></pre>