【问题标题】:finding first three maximum element and their index of a vector找到前三个最大元素及其向量的索引
【发布时间】:2015-06-01 07:25:42
【问题描述】:

我有一个看起来像这样的向量

[12,3,4,5,6,7,8,12]

我想找到前三个最大数的索引和值。最大数也可以像上面的向量一样重复12次重复。

我用过

哪个

但它只返回一个数字的索引如何做到这一点

输出

[12,12,8]
[1,8,7]

我也读过这个Stack Overflow,但没有帮助

【问题讨论】:

  • 查看函数 sort.int 及其参数 decreasingindex.return

标签: r vector


【解决方案1】:
x <- c(12, 3, 4, 5, 6, 7, 8, 12)
sort.int(x, decreasing = TRUE, index.return = TRUE)
# $x
# [1] 12 12  8  7  6  5  4  3

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

然后,前三个元素:

sort.int(x, decreasing = TRUE, index.return = TRUE)$ix[1:3]
# [1] 1 8 7

【讨论】:

  • sortsort.int 除了sort.int 不适用于data.frames 中的多个列之外,还有什么区别吗?喜欢sort.intbeeing 更快?
  • 我不是原帖,我只是想知道你为什么用sort.int而不是sort,这有什么好处
  • 啊,是的,对不起。它几乎完全一样。您可以阅读?sort 找到更多详细信息。但基本上,在大多数情况下,您可以改用sort(x, decreasing = TRUE, index.return = TRUE)
【解决方案2】:

只需按降序对向量进行排序,然后选择前三项:

vec <- c(12,3,4,5,6,7,8,12)

# gives the biggest three elements
sort(vec, decreasing = TRUE)[1:3]
# gives the indices of the first three elements
order(vec, decreasing = TRUE)[1:3]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2014-06-28
    • 2012-12-17
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多