How to get ranks with no gaps when there are ties among values?

后端 未结 8 1300
感情败类
感情败类 2020-12-03 14:26

When there are ties in the original data, is there a way to create a ranking without gaps in the ranks (consecutive, integer rank values)? Suppose:

x <-           


        
8条回答
  •  醉酒成梦
    2020-12-03 15:08

    Another function that does this, but it seems inefficient. There is no for loop, but I doubt it is more efficient than Sacha's suggestion!

    x=c(1,1,2,3,4,5,8,8)
    fancy.rank <- function(x) {
        x.unique <- unique(x)
        d1 <- data.frame(x=x)
        d2 <- data.frame(x=x.unique, rank(x.unique))
        merge(d1, d2, by="x")[,2]
    }
    
    fancy.rank(x)
    
    [1] 1 1 2 3 4 5 6 6
    

提交回复
热议问题