问题
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