Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ranking

rank

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
like image 408
theforestecologist Avatar asked Oct 28 '25 11:10

theforestecologist


1 Answers

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
like image 200
jalapic Avatar answered Oct 31 '25 09:10

jalapic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!