Reputation: 1121
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
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