title: R, dplyr: assign number of occurence as value to column at several group_by() levels
body: <pre><code>require(plyr)
  require(dplyr)
  
  set.seed(8)
  df &lt;- data.frame(
    group = sample(c("A","B"), 10, replace=T),
    subgroup = sample(c("a", "b", "c"),10, replace=T),
    value = runif(10, -1,1)
    )
  df %&gt;% arrange(group,subgroup)
  </code></pre>
  
  <p>gives:</p>
  
  <pre><code>         group subgroup      value
  1      A        a -0.1841505
  2      A        a  0.3265360
  3      A        a -0.8045035
  4      A        b -0.5526222
  5      B        a  0.2238653
  6      B        a  0.0552373
  7      B        b  0.2297515
  8      B        b -0.5700525
  9      B        b  0.6347312
  10     B        c  0.9550054
  </code></pre>
  
  <p>I can indicate whether value is high or low, eg:</p>
  
  <pre><code>df2&lt;-
  df %&gt;% mutate(reg = ifelse(value &gt; 0, "high", "low"))
  df2
  </code></pre>
  
  <p>gives:</p>
  
  <pre><code>   group subgroup      value  reg
  1      A        b -0.5526222  low
  2      A        a -0.1841505  low
  3      B        b  0.2297515 high
  4      B        b -0.5700525  low
  5      A        a  0.3265360 high
  6      B        c  0.9550054 high
  7      A        a -0.8045035  low
  8      B        a  0.2238653 high
  9      B        a  0.0552373 high
  10     B        b  0.6347312 high
  </code></pre>
  
  <p>Problem:
  I would like to get columns <code>low.group</code>, <code>high.group</code>,<code>low.subgroup</code> and <code>high.subgroup</code> indicating how many times high and low values are found at the group (I thought of <code>dplyr</code>'s <code>group_by(group)</code> and <code>n()</code>, perhaps with <code>summarise()</code>) and at the group+subgroup level (<code>group_by(group, subgroup)</code>). This would generate a 6 row by 6 column data frame (combinations of A/B and a/b/c, and columns <code>group</code>, <code>subgroup</code>, <code>low.group</code>, <code>high.group</code>,<code>low.subgroup</code> and <code>high.subgroup</code>). First column should read (A, a, 3, 1, 2, 1), second (A, b, 3, 1, 1, 0) etc.
  I can make counts e.g. by:</p>
  
  <pre><code>df %&gt;%
  group_by(group,reg) %&gt;%
  mutate(n.group=n())
  </code></pre>
  
  <p>But how do I split <code>n.group</code> into the two columns <code>low.group</code> and <code>high.group</code>. Same problem for the subgroups.</p>
  
  <p>I am sure the functions in <code>plyr</code>, <code>dplyr</code> and <code>reshape2</code> can do this combined counting and summarization but how?</p>
  
  <p>UPDATE:
  Here is the hand-made result that I would get:</p>
  
  <pre><code>group   subgroup    low.group   high.group  low.subgroup    high.subgroup
  A   a   3   1   2   1
  A   b   3   1   1   0
  A   c   3   1   0   0
  B   a   1   5   0   1
  B   b   1   5   1   2
  B   c   1   5   0   1
  </code></pre>