如何根据标记在数据框中创建排名,但排名应根据性别分开:
Sl.no Name Gender Marks Rank
1 aa Male 77 3
2 bb Female 80 2
3 cc Male 74 4
4 dd Female 72 5
5 ee Male 87 1
6 ff Female 80 3
7 gg Male 72 5
8 hh Female 84 1
9 ii Male 82 2
10 jj Female 79 4
答案 0 :(得分:2)
我们可以按操作使用组
library(data.table)
setDT(df1)[order(-Marks), Rank := seq_len(.N), by = Gender]
df1
# Sl.no Name Gender Marks Rank
#1: 1 aa Male 77 3
#2: 2 bb Female 80 2
#3: 3 cc Male 74 4
#4: 4 dd Female 72 5
#5: 5 ee Male 87 1
#6: 6 ff Female 80 3
#7: 7 gg Male 72 5
#8: 8 hh Female 84 1
#9: 9 ii Male 82 2
#10: 10 jj Female 79 4
或dplyr
library(dplyr)
df1 %>%
group_by(Gender) %>%
arrange(Gender, desc(Marks)) %>%
mutate(Rank = row_number())