title: dataframes in R with multi-level rows and columns
body: <p>Let's say I have the following data frame.</p>
  
  <pre><code>&gt; df = data.frame(rowsA = sample(c('A','B','C'), 100, replace=TRUE),
                  rowsB = sample(c('D','E','F'), 100, replace=TRUE),
                  colsA = sample(c('G','H','I'), 100, replace=TRUE),
                  colsB = sample(c('J','K','L'), 100, replace=TRUE))
  
  &gt; head(df)
    rowsA rowsB colsA colsB
  1     B     E     I     L
  2     A     E     G     J
  3     A     E     H     K
  4     A     D     I     J
  5     C     F     G     J
  6     A     F     G     J
  </code></pre>
  
  <p>Is it possible to create a multi-level table of counts?</p>
  
  <p>In excel, it is possible with the PivotTable functionality</p>
  
  <p><a href="https://i.stack.imgur.com/NVrHL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NVrHL.png" alt="enter image description here"></a></p>
  
  <p>I think it possible in python in pandas with the df.columns.levels method.</p>
  
  <p>I also figured out how to do multi-level rows only in R with dplyr (but haven't figured out multi-level columns)</p>
  
  <pre><code>df %&gt;%
      group_by(rowsA, rowsB, colsA) %&gt;%
      summarise(count = n()) %&gt;%
      spread(colsA, count)
  
  # A tibble: 9 x 5
  # Groups:   rowsA, rowsB [9]
     rowsA  rowsB     G     H     I
  * &lt;fctr&gt; &lt;fctr&gt; &lt;int&gt; &lt;int&gt; &lt;int&gt;
  1      A      D     5     3     1
  2      A      E     1     2     1
  3      A      F     5     8    NA
  4      B      D     5     5     5
  5      B      E     2     4     6
  6      B      F     4     6     5
  7      C      D     2     6    NA
  8      C      E     6     5     3
  9      C      F     4     3     3
  </code></pre>