首页 > 解决方案 > 如何在不重复排名的情况下对 R 中的向量进行排序

问题描述

下午好 ,

我的问题可能看起来很初级,但我遇到了麻烦。

假设我们有以下向量:

x=c(0.75,0.75,1,1,0.5,0.5,0.5,0.25,0.25)

我愿意对向量进行递减排序,然后获取索引,这意味着:

sort.int(x, index.return=TRUE,decreasing=TRUE)
$x
[1] 1.00 1.00 0.75 0.75 0.50 0.50 0.50 0.25 0.25

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

但是,预期的输出应该是:

y=c(2,2,1,1,3,3,3,4,4)

这表示 :

1 is the highest value ----- > 1 
0.75 is the second highest value ----- > 2
0.5 is the third ----- > 3
0.25 is the lowest value -----> 4

我也试过:

x=c(0.75,0.75,1,1,0.5,0.5,0.5,0.25,0.25)

order(unique(sort(x)))

sort(unique(x),decreasing=TRUE)

[1] 1 2 3 4
[1] 1.00 0.75 0.50 0.25

但我不知道如何从子集x得到预期的输出 y

谢谢你的帮助 !

标签: r

解决方案


sort将对所有值进行排序,并使用每个值一次。似乎您想在第一个之后忽略重复值的索引。我们可以使用match它,它总是返回第一个匹配的索引。

match(sort.int(x, decreasing = TRUE), unique(x))
# [1] 2 2 1 1 3 3 3 4 4

推荐阅读