使用 dplyr 创建排名变量? [英] Create a ranking variable with dplyr?
本文介绍了使用 dplyr 创建排名变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下数据
df = data.frame(name=c("A", "B", "C", "D"), score = c(10, 10, 9, 8))
我想添加一个带有排名的新列.这就是我正在做的:
I want to add a new column with the ranking. This is what I'm doing:
df %>% mutate(ranking = rank(score, ties.method = 'first'))
# name score ranking
# 1 A 10 3
# 2 B 10 4
# 3 C 9 2
# 4 D 8 1
然而,我想要的结果是:
However, my desired result is:
# name score ranking
# 1 A 10 1
# 2 B 10 1
# 3 C 9 2
# 4 D 8 3
显然 rank
不符合我的想法.我应该使用什么功能?
Clearly rank
does not do what I have in mind. What function should I be using?
推荐答案
听起来您正在从dplyr"中寻找 dense_rank
-- 但应用的顺序与 的顺序相反排名
通常是.
It sounds like you're looking for dense_rank
from "dplyr" -- but applied in a reverse order than what rank
normally does.
试试这个:
df %>% mutate(rank = dense_rank(desc(score)))
# name score rank
# 1 A 10 1
# 2 B 10 1
# 3 C 9 2
# 4 D 8 3
这篇关于使用 dplyr 创建排名变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文