【问题标题】:Efficient way to get the rank of the min of a vector in R?获得R中向量最小值的有效方法?
【发布时间】:2015-05-23 19:07:55
【问题描述】:

R中是否有一种有效的方法来获得向量(列表)的最小值(最大值)的排名?

我会使用 min 函数找到最小值

p = min(x)

然后使用for循环在x中搜索p的排名...

更好地利用 R 功能?

【问题讨论】:

  • 我想你不知道等级是什么。如果它是唯一的,则最小值的等级为 1。如果是平局,其排名取决于平局规则。

标签: r optimization vector minimum rank


【解决方案1】:

函数order 为您提供了放置向量的顺序,如果您想订购它。 因此,如果x 是您的向量,
order(x)[1] 为您提供min 的索引,
order(x)[length(x)](或order(x, decreasing=T)[1])为您提供max 的索引。

示例

set.seed(123)
x <- rnorm(10)
x
# [1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774  1.71506499  0.46091621 -1.26506123 -0.68685285
#[10] -0.44566197

# Now, compute the vector of ordered indices with order
ord_x <- order(x)

# get the index of the min
ord_x[1]
#[1] 8

# get the index of the max
ord_x[length(ord_x)]
#[1] 6

# you can check that you have the right indices:
x[8]==min(x)
#[1] TRUE
x[6]==max(x)
#[1] TRUE

【讨论】:

    【解决方案2】:

    您是否正在寻找向量中最小值的索引?

    有一个函数,which.min,例如

    which.min(c(15, 1, 5))
    # 2
    

    【讨论】:

      猜你喜欢
      • 2011-08-28
      • 2012-04-10
      • 2019-10-20
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多