title: Calculate ranks for each group
body: <p>I have a <code>df</code> with types and values. I want to rank them in order of <code>x</code> within <code>type</code> and give a count of how many other rows row <code>n</code> has  higher value of <code>x</code> than (column <code>pos</code>).</p>
  
  <p>e.g. </p>
  
  <pre><code>df &lt;- data.frame(type = c("a","a","a","b","b","b"),x=c(1,77,1,34,1,8))
  # for type a row 3 has a higher x than row 1 and 2 so has a pos value of 2
  </code></pre>
  
  <p>I can do this with:</p>
  
  <pre><code>library(plyr)
  df &lt;- data.frame(type = c("a","a","a","b","b","b"),x=c(1,77,1,34,1,8))
  df &lt;- ddply(df,.(type), function(x) x[with(x, order(x)) ,])
  df &lt;- ddply(df,.(type), transform, pos = (seq_along(x)-1) )
  
       type  x pos
  1    a  1   0
  2    a  1   1
  3    a 77   2
  4    b  1   0
  5    b  8   1
  6    b 34   2
  </code></pre>
  
  <p>But this approach does not take into account ties between type <code>a</code> row 1 and 2. Whats the easiest way to get the output where ties have the same value e.g.</p>
  
  <pre><code>     type  x pos
   1    a  1   0
   2    a  1   0
   3    a 77   2
   4    b  1   0
   5    b  8   1
   6    b 34   2
  </code></pre>