Add a “rank” column to a data frame

There is a rank function to help you with that:

transform(df, 
          year.rank = ave(count, year, 
                          FUN = function(x) rank(-x, ties.method = "first")))
  item year count year.rank
1    a 2010     1         3
2    b 2010     4         2
3    c 2010     6         1
4    a 2011     3         2
5    b 2011     8         1
6    c 2011     3         3
7    a 2012     5         3
8    b 2012     7         2
9    c 2012     9         1

Leave a Comment