R 从排序到排序再返回
R 从排序到排序再返回,r,sorting,vector,R,Sorting,Vector,sort和order分别返回有序值的向量和有序值的索引 使用order实现sort很简单: v <- c(17, -5, 1, 20) identical(v[order(v)], sort(v)) [1] 真的 不漂亮。有更简单的方法吗?在排序功能中返回索引: sort(v, index.return=TRUE) #$x #[1] -5 1 17 20 #$ix #[1] 2 3 1 4 # this is the order to sort the vector
sort
和order
分别返回有序值的向量和有序值的索引
使用order
实现sort
很简单:
v <- c(17, -5, 1, 20)
identical(v[order(v)], sort(v))
[1] 真的
不漂亮。有更简单的方法吗?在
排序功能中返回索引:
sort(v, index.return=TRUE)
#$x
#[1] -5 1 17 20
#$ix
#[1] 2 3 1 4 # this is the order to sort the vector
idential(match(sort(v),v),order(v))
请注意,问题的解决方案取决于是否存在重复项。@G.Grothendieck,idential(match(make.unique)(as.character(sort(v))、make.unique(as.character(v))、order(v))
可能会处理重复项hanks d.b!好球@G.Grothendieck<代码>制造。唯一性
是d.b.评论中需要的。抱歉。你是对的。
sort(v, index.return=TRUE)
#$x
#[1] -5 1 17 20
#$ix
#[1] 2 3 1 4 # this is the order to sort the vector
identical(sort(v, index.return=TRUE)$ix, order(v))
# [1] TRUE