title: Ranking elements within a data.frame
body: <p>Let's say I have a data frame, like this: </p>
  
  <pre><code>df &lt;- data.frame(
    variable = rep(letters[1:10], 2),
    y2 = 1:10,
    y1 = c(10, 9, 8 ,7, 6, 5, 4, 2, 1, 3),
    stat = c(rep(letters[1], 10), rep(letters[2], 10))
  )
  </code></pre>
  
  <p>By "stat", I would like to create three new columns, one that shows a numbered rank for <code>y1</code> and <code>y2</code>, and another that calculates the change in rank between <code>y1</code> and <code>y2</code> (short for year 1 and year 2). </p>
  
  <p>I've been tinkering with <code>ddply</code>, but I can't seem to get it to do what I want. Here's an example of what I've tried (which may also illustrate what I'm attempting to do): </p>
  
  <pre><code>ddply(df, .(stat), function(x) data.frame(
    df,
    y1rank = rank(x$x),
    y2rank = rank(x$y),
    change = rank(x$y) - rank(x$x)
  ))
  </code></pre>