Calculate the rank of each index in a vector

微笑、不失礼 提交于 2019-12-22 09:24:17

问题


I'd like to calculate the rank of each index within a vector, e.g:

x <- c(0.82324952352792, 0.11953364405781, 0.588659686036408, 0.41683742380701, 
       0.11452184105292, 0.438547774450853, 0.586471405345947, 0.943002870306373, 
       0.28184655145742, 0.722095313714817)

calcRank <- function(x){
  sorted <- x[order(x)]
  ranks <- sapply(x, function(x) which(sorted==x))
  return(ranks)
}

calcRank(x)

> calcRank(x)
 [1]  9  2  7  4  1  5  6 10  3  8

Is there a better way to do this?


回答1:


Why not just:

rank(x)     # ..... ?

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



回答2:


match is what you want:

match(x, sort(x))


来源:https://stackoverflow.com/questions/11002920/calculate-the-rank-of-each-index-in-a-vector

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