Search code examples
rsortingcriteriarank

Is there an easy way to rank values in R using two criteria (the second one being for the ties)?


I have been wondering whether there is a simple way of ranking values in R with two criteria: one for the main ranking and the other to rank the ties.

For instance, suppose we have the following sets of number:

a <- c(9,13,6,3,7,1,13)
b <- c(1,4,3,6,5,7,2)

Now, suppose we want to rank a using the information in b to handle the ties in rank(a), so we end up having the following:

> 5 7 3 2 4 1 6

Is there an easy way to get that in R? The options in rank to deal with ties are of no help for that.

PS: there is a similar question on rank and ties already, but it's not a duplicate since it's not really asking the same thing despite its title suggesting so: Is there a simple way to rank on multiple criteria that preserves ties in R?


Solution

  • Assuming that all ties are actually broken:

    order(order(a, b))
    #[1] 5 7 3 2 4 1 6
    

    There are probably more efficient alternatives.