title: Getting the top values by group
body: <p>Here's a sample data frame:</p>
  
  <pre><code>d &lt;- data.frame(
    x   = runif(90),
    grp = gl(3, 30)
  ) 
  </code></pre>
  
  <p>I want the subset of <code>d</code> containing the rows with the top 5 values of <code>x</code> for each value of <code>grp</code>.</p>
  
  <p>Using base-R, my approach would be something like:</p>
  
  <pre><code>ordered &lt;- d[order(d$x, decreasing = TRUE), ]    
  splits &lt;- split(ordered, ordered$grp)
  heads &lt;- lapply(splits, head)
  do.call(rbind, heads)
  ##              x grp
  ## 1.19 0.8879631   1
  ## 1.4  0.8844818   1
  ## 1.12 0.8596197   1
  ## 1.26 0.8481809   1
  ## 1.18 0.8461516   1
  ## 1.29 0.8317092   1
  ## 2.31 0.9751049   2
  ## 2.34 0.9269764   2
  ## 2.57 0.8964114   2
  ## 2.58 0.8896466   2
  ## 2.45 0.8888834   2
  ## 2.35 0.8706823   2
  ## 3.74 0.9884852   3
  ## 3.73 0.9837653   3
  ## 3.83 0.9375398   3
  ## 3.64 0.9229036   3
  ## 3.69 0.8021373   3
  ## 3.86 0.7418946   3
  </code></pre>
  
  <p>Using <code>dplyr</code>, I expected this to work:</p>
  
  <pre><code>d %&gt;%
    arrange_(~ desc(x)) %&gt;%
    group_by_(~ grp) %&gt;%
    head(n = 5)
  </code></pre>
  
  <p>but it only returns the overall top 5 rows.</p>
  
  <p>Swapping <code>head</code> for <a href="http://www.inside-r.org/packages/cran/dplyr/docs/top_n"><code>top_n</code></a> returns the whole of <code>d</code>.</p>
  
  <pre><code>d %&gt;%
    arrange_(~ desc(x)) %&gt;%
    group_by_(~ grp) %&gt;%
    top_n(n = 5)
  </code></pre>
  
  <p>How do I get the correct subset?</p>