title: R dplyr's group_by consider empty groups as well
body: <p>Let's consider the following data frame:</p>
  
  <pre><code>set.seed(123)
  data &lt;- data.frame(col1 = factor(rep(c("A", "B", "C"), 4)),
                     col2 = factor(c(rep(c("A", "B", "C"), 3), c("A", "A", "A"))),
                     val1 = 1:12,
                     val2 = rnorm(12, 10, 15))
  </code></pre>
  
  <p>The contingency table is as follows:</p>
  
  <pre><code>cont_tab &lt;- table(data$col1, data$col2, dnn = c("col1", "col2"))
  
  cont_tab
  
      col2
  col1 A B C
     A 4 0 0
     B 1 3 0
     C 1 0 3
  </code></pre>
  
  <p>As you can see some pairs didn't occur: (A,B), (A,C), (B,C), (C,B). The end goal of my analysis is to list all of the pairs (in this case 9) and show a statistic for each of them. While using <code>dplyr::group_by()</code> function I hit a limitation. Namely, the <code>dplyr::group_by()</code> considers only existing pairs (pairs that occured at least once):</p>
  
  <pre><code>data %&gt;%
    group_by(col1, col2) %&gt;%
    summarize(stat = sum(val2) - sum(val1))
  
  # A tibble: 5 x 3
  # Groups:   col1 [?]
    col1  col2   stat
    &lt;fct&gt; &lt;fct&gt; &lt;dbl&gt;
  1 A     A      58.1
  2 B     A     -16.4
  3 B     B      17.0
  4 C     A     -12.9
  5 C     C     -41.9
  </code></pre>
  
  <p>The output I have in mind has 9 rows (4 of which has <code>stat</code> equal to 0). Is it doable in <code>dplyr</code>?</p>
  
  <p>EDIT: Sorry for being too vague at the beginning. The real problem is more complex than counting the number of times a particular pair occurs. I added the new data in order to make the real problem more visible.</p>