【问题标题】:Going from sort to order and back从排序到排序再返回
【发布时间】:2018-04-29 00:18:41
【问题描述】:

sortorder 分别返回有序值的向量和有序值的索引。

使用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 的评论中是必需的。
  • 对不起。你是对的。

标签: r sorting vector


【解决方案1】:

返回sort函数中的索引:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2016-06-13
    • 2015-04-20
    相关资源
    最近更新 更多