How do I preserve continuous (1,2,3,…n) ranking notation when ranking in R?

孤街醉人 提交于 2019-11-28 05:41:34

问题


If I want to rank a set of numbers using the minimum rank for shared cases (aka ties):

dat <- c(13,13,14,15,15,15,15,15,15,16,17,22,45,46,112)
rank(dat, ties = 'min')

I get the results:

 1  1  3  4  4  4  4  4  4 10 11 12 13 14 15

However, I want the rank to be a continuous series consisting of 1,2,3,...n, where n is the number of unique ranks.

Is there a way to make rank (or a similar function) rank a series of numbers by assigning ties to the lowest rank as above but instead of skipping subsequent rank values by the number of previous ties to instead continue ranking from the previous rank?

For example, I would like the above ranking to result in:

1  1  2  3  3  3  3  3  3  4  5  6  7  8  9

回答1:


you could do it using dplyr:

library(dplyr)
dense_rank(dat)

 [1] 1 1 2 3 3 3 3 3 3 4 5 6 7 8 9

if you don't want to load the whole library and do it in base r:

r<-rank(dat, na.last = "keep")
match(r, sort(unique(r)))

 [1] 1 1 2 3 3 3 3 3 3 4 5 6 7 8 9



回答2:


Use a factor and then bring it back to numeric format:

as.numeric(factor(rank(dat)))
# [1] 1 1 2 3 3 3 3 3 3 4 5 6 7 8 9


来源:https://stackoverflow.com/questions/36189967/how-do-i-preserve-continuous-1-2-3-n-ranking-notation-when-ranking-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!