【问题标题】:Return index of the smallest value in a vector?返回向量中最小值的索引?
【发布时间】:2012-02-22 07:33:11
【问题描述】:
a <- c(1, 2, 0, 3, 7)

我正在寻找一个函数来返回最小值的索引,3。它是什么?

【问题讨论】:

    标签: r


    【解决方案1】:

    你在找which.min()

    a <- c(1,2,0,3,7,0,0,0)
    which.min(a)
    # [1] 3
    
    which(a == min(a))
    # [1] 3 6 7 8
    

    (从上面可以看出,当多个元素被绑定为最小值时,which.min() 只返回第一个的索引。如果您想要所有匹配的元素的索引,则可以使用第二个构造最小值。)

    【讨论】:

    • ...是的,我想知道如何获得所有最小元素的索引?我需要找出最少有多少,完美!给我一些时间来理解这一点,谢谢。
    • @hhh -- 要找出最少有多少个元素,您可以使用:sum(a == min(a))
    【解决方案2】:

    作为乔希回答的替代方案

    a <- c(1, 2, 0, 3, 7)
    which(a == min(a))
    

    这给出了等于最小值的每个索引。因此,如果我们有多个值匹配最低值

    a <- c(1, 2, 0, 3, 7, 0)
    which(a == min(a))  # returns both 3 and 6
    which.min(a)        # returns just 3
    

    编辑:如果您正在寻找的只是有多少元素等于最小值(正如您在其中一个 cmets 中暗示的那样),您可以这样做:

    a <- c(1, 2, 0, 3, 7, 0)
    sum(a == min(a))
    

    【讨论】:

      【解决方案3】:

      如果你喜欢效率,那么你可以使用 Rfast 包中的 min_max 函数,index = True

      它将返回最小值的索引和最大值的索引 同时,价值比目前没有使用的更快。

      例如

      a = runif(10000)
      Rfast::min_max(a,index=T)
      
      # min  max 
      # 2984 2885
      
      which(a == min(a))
      
      #[1] 2984
      
      a = runif(1000000)
      microbenchmark::microbenchmark(
          min_max = Rfast::min_max(a,index=T),
          which1 = which(a == min(a)),
          which2 = which.min(a)
      )
      
      Unit: milliseconds
         expr      min         lq        mean     median         uq        max neval
      min_max 1.889293  1.9123860  2.08242647  1.9271395  2.0359730   3.527565   100
       which1 9.809527 10.0342505 13.16711078 10.3671640 14.7839955 111.424664   100
       which2 2.400745  2.4216995  2.66374110  2.4471435  2.5985265   4.259249   100
      

      【讨论】:

      • 不幸的是,Rfast::min_max 也只会返回一个(第一个?似乎没有记录)领带,因此与 which(a == min(a)) 相比是不公平的,这仅在一个人想要所有分钟时才相关!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2016-09-16
      • 2017-02-26
      • 2015-04-29
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多