title: How to get two-way tables with marginal proportions?
body: <p>Consider this</p>
  
  <pre><code>var1&lt;- c('A','B','C','C','G')
  var2&lt;- c('G','B','B','F','A')
  df = df=data.frame(var1,var2)
  
  &gt; df
    var1 var2
  1    A    G
  2    B    B
  3    C    B
  4    C    F
  5    G    A
  </code></pre>
  
  <p>I want to get a two-way table between <code>var1</code> and <code>var2</code>.</p>
  
  <p>I can use </p>
  
  <pre><code>&gt; df %&gt;% count(var1,var2) %&gt;% spread(var2, n, fill = 0)
  Source: local data frame [4 x 5]
  Groups: var1 [4]
  
      var1     A     B     F     G
  * &lt;fctr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
  1      A     0     0     0     1
  2      B     0     1     0     0
  3      C     0     1     1     0
  4      G     1     0     0     0
  </code></pre>
  
  <p>or using <code>table</code></p>
  
  <pre><code>&gt; table( df$var1, df$var2)
  
      A B F G
    A 0 0 0 1
    B 0 1 0 0
    C 0 1 1 0
    G 1 0 0 0
  </code></pre>
  
  <p>Both give the same results. But now suppose I am interested in the row or columns proportions. I can use <code>table</code> again here</p>
  
  <pre><code>&gt; prop.table(table( df$var1, df$var2), margin =2) # for column
  
        A   B   F   G
    A 0.0 0.0 0.0 1.0
    B 0.0 0.5 0.0 0.0
    C 0.0 0.5 1.0 0.0
    G 1.0 0.0 0.0 0.0
  
  &gt; prop.table(table( df$var1, df$var2), margin =1) # for rows
  
        A   B   F   G
    A 0.0 0.0 0.0 1.0
    B 0.0 1.0 0.0 0.0
    C 0.0 0.5 0.5 0.0
    G 1.0 0.0 0.0 0.0
  </code></pre>
  
  <p>How can I reproduce these with <code>dplyr</code> (the shortest syntax)?</p>
  
  <p>The solution below seems to work (only in one case), although I don't understand why: what does the <code>prop.table(n)</code> function does here? </p>
  
  <pre><code>&gt; df %&gt;%  count(var1,var2) %&gt;% mutate(prop = prop.table(n)) %&gt;% spread(var2, prop, fill = 0)
  Source: local data frame [4 x 6]
  Groups: var1 [4]
  
      var1     n     A     B     F     G
  * &lt;fctr&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
  1      A     1     0   0.0   0.0     1
  2      B     1     0   1.0   0.0     0
  3      C     1     0   0.5   0.5     0
  4      G     1     1   0.0   0.0     0
  </code></pre>
  
  <p>Also, using <code>margin</code> in prop.table fails here.</p>
  
  <pre><code>&gt; df %&gt;%  count(var1,var2) %&gt;% mutate(prop = prop.table(n ,margin =1)) %&gt;% spread(var2, prop, fill = 0)
  Error in eval(substitute(expr), envir, enclos) : 'x' is not an array
  </code></pre>
  
  <p>Thanks!</p>