Question

I want to rank a column of a data frame but I want it to be ranked based on its order not ascending or descending order. Something like below:

> test <- c(0,0,0,2,1,5,3)

and then rank like this:

[1] 1 1 1 2 3 4 5

What is the easiest way of doing it? Thank you in advance.

Was it helpful?

Solution

Use rle:

test = c(0,0,0,2,1,5,3)
rle_test = rle(test)
ordered = rep(1:length(rle_test$lengths), rle_test$lengths)

Output:

> ordered
[1] 1 1 1 2 3 4 5

OTHER TIPS

An alternative would use the ties="dense" option of frankv() in data.table package:

x

[1] 12 9 5 7 15 7 7 8 7 13 6 12 7 12 5 2 8 28 20 9 10 3 12 6 1

frankv(x,ties="dense")

[1] 10 8 4 6 12 6 6 7 6 11 5 10 6 10 4 2 7 14 13 8 9 3 10 5 1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top