Calculate average ranking in R

Here is short post to describe how to calculate the average rank from a set of multiple ranks listed in different
data.frames in R. This is a fairly straightforward procedure, however, it took me more time than I anticipated to make this
work.

To begin with, let's create a set of data.frames with and randomly assign them rank values from 1 to 5 for the letters
A,B,C,D,E:

For A, B, C, D and E, we can quite easily calculate the average ranks. To do this, using the sapply command, we can create a
matrix of all the rankings for each data frame with a column for each of the five sets of rankings and a row for each of A
through E:

Next, we calculate the mean for each of A, B, C, D and E using the built-in R function rowMeans:

Finally we use the order function to get the final rank values and convert the vector back into a data.frame which is of
the same format as the original rank data.frames:

I hope this was of use to someone, even if that person happens to a forgetful future me. I'm more than certain that
there is an R function or an R package which will perform this for you but it is nonetheless at most interesting and at
least fun to implement. If anyone has an alternative, more elegant solution, I would really appreciate hearing from you.
Happy hacking!

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *