Grec001
Grec001

Reputation: 1121

How to make a true ranking by giving same ranking to same score while the rest follow the true order?

Here is the toy sample of 8 students with grades from A to D. I would like to give a ranking which reflects the true order while students with same grade shall have same ranking. It seems the .GRP is most likely the right approach, but it goes with order of numbers, how can I skip the position occupied by the students with same grade, with data.table? Thanks.

DT <- data.table(GRADE = c("A","B","B","C",rep("D",4)))
DT[, GRP:=.GRP, by = GRADE][, RANK:= c(1,2,2,4,5,5,5,5)]

#   GRADE GRP RANK
#1:     A   1    1
#2:     B   2    2
#3:     B   2    2
#4:     C   3    4
#5:     D   4    5
#6:     D   4    5
#7:     D   4    5
#8:     D   4    5

Upvotes: 1

Views: 195

Answers (1)

akrun
akrun

Reputation: 887128

An option is frank

DT[, RANK := frank(GRADE, ties.method = 'min')]
DT$RANK
#[1] 1 2 2 4 5 5 5 5

Or in dplyr with min_rank

library(dplyr)
DT %>% 
   mutate(RANK = min_rank(GRADE))

Upvotes: 1

Related Questions