R group by and aggregate - return relative rank within groups using plyr

后端 未结 2 528
时光说笑
时光说笑 2021-01-16 22:50

UPDATE: I have a data frame \'test\' that look like this:

    session_id  seller_feedback_score
1   1   282470
2   1   275258
3   1   275258
4   1   275258
5         


        
2条回答
  •  粉色の甜心
    2021-01-16 23:16

    One option:

    library(dplyr)
    df %>% group_by(session_id) %>% 
      mutate(rank = dense_rank(-seller_feedback_score))
    

    dense_rank is "like min_rank, but with no gaps between ranks" so I negated the seller_feedback_score column in order to turn it into something like max_rank (which doesn't exist in dplyr).

    If you want the ranks with gaps so that you reach 21 for the lowest in your case, you can use min_rank instead of dense_rank:

    library(dplyr)
    df %>% group_by(session_id) %>% 
        mutate(rank = min_rank(-seller_feedback_score))
    

提交回复
热议问题