【发布时间】:2018-04-29 00:18:41
【问题描述】:
sort 和 order 分别返回有序值的向量和有序值的索引。
使用order实现sort很简单:
v <- c(17, -5, 1, 20)
identical(v[order(v)], sort(v))
[1] 是的
使用sort实现order最直接的方法是什么?
这是我想出的:
identical(sapply(sort(v), function(x) grep(paste0("^", x, "$"), v)), order(v))
[1] 是的
不漂亮。有没有更简单的方法?
【问题讨论】:
-
identical(match(sort(v), v), order(v)) -
请注意,问题中的解决方案取决于没有重复。
-
@G.Grothendieck,
identical(match(make.unique(as.character(sort(v))), make.unique(as.character(v))), order(v))可能会处理重复项 -
谢谢d.b!很好的捕捉@G.Grothendieck。
make.unique在 d.b 的评论中是必需的。 -
对不起。你是对的。