Search code examples
rrankingrank

How do I preserve continuous (1,2,3,...n) ranking notation when ranking in R?


If I want to rank a set of numbers using the minimum rank for shared cases (aka ties):

dat <- c(13,13,14,15,15,15,15,15,15,16,17,22,45,46,112)
rank(dat, ties = 'min')

I get the results:

 1  1  3  4  4  4  4  4  4 10 11 12 13 14 15

However, I want the rank to be a continuous series consisting of 1,2,3,...n, where n is the number of unique ranks.

Is there a way to make rank (or a similar function) rank a series of numbers by assigning ties to the lowest rank as above but instead of skipping subsequent rank values by the number of previous ties to instead continue ranking from the previous rank?

For example, I would like the above ranking to result in:

1  1  2  3  3  3  3  3  3  4  5  6  7  8  9

Solution

  • you could do it using dplyr:

    library(dplyr)
    dense_rank(dat)
    
     [1] 1 1 2 3 3 3 3 3 3 4 5 6 7 8 9
    

    if you don't want to load the whole library and do it in base r:

    match(dat, sort(unique(dat)))
    
     [1] 1 1 2 3 3 3 3 3 3 4 5 6 7 8 9