r - 如何在不重复排名的情况下对 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
。
谢谢你的帮助 !
解决方案
sort
将对所有值进行排序,并使用每个值一次。似乎您想在第一个之后忽略重复值的索引。我们可以使用match
它,它总是返回第一个匹配的索引。
match(sort.int(x, decreasing = TRUE), unique(x))
# [1] 2 2 1 1 3 3 3 4 4
推荐阅读
- php - Woocommerce 编辑器中的简码不显示
- reactjs - 使用 React Router 时组件不可见
- android - 为什么新的地方 sdk 客户端兼容性脚本给我 - “访问被拒绝”
- mysql - 将汇总的 SQL 语句
- javascript - 如何处理量角器中发生的错误/异常?
- r - 根据列拆分数据集
- javascript - JavaScript 闭包变量在实例之间共享
- ag-grid - agSetColumnFilter 出现服务器端分页错误
- ruby-on-rails - 用于 nil:NilClass 的 link_thumbnailer 未定义方法“src”
- angular - 在 Angular 6 组件之间共享使用 HTTP GET 加载的数据