r 中的排名列不跳过领带

ranking column in r without skipping ties

我想对有平局的列进行排名,但如果有平局则不跳过下一个数字。目前我做的时候:

A         B
group1   325
group1   325
group1   123 

C <- df %>% 
  group_by(A) %>%
  mutate(rank(-B, ties.method = "min")) %>%
  ungroup()

我明白了

A         B   C
group1   325  1
group1   325  1
group1   123  3

有没有办法让它不跳过数字2?

我们可以使用dense_rank

library(dplyr)
df %>% 
   group_by(A) %>%
   mutate(C = dense_rank(-B)) %>%
   ungroup

-输出

# A tibble: 3 × 3
  A          B     C
  <chr>  <int> <int>
1 group1   325     1
2 group1   325     1
3 group1   123     2

数据

df <- structure(list(A = c("group1", "group1", "group1"), B = c(325L, 
325L, 123L)), class = "data.frame", row.names = c(NA, -3L))