【问题标题】:return index from a vector of the value closest to a given element从最接近给定元素的值的向量返回索引
【发布时间】:2013-02-19 22:38:33
【问题描述】:

我有一个元素列表,例如

A=
  0.992688
  0.892195
  0.889151
  0.380672
  0.180576
  0.685028
  0.58195

给定一个输入元素,例如 0.4,我如何找到包含最接近该数字的数字的索引。例如,A[4] = 0.380672 最接近 0.4。因此,它应该返回到 4

【问题讨论】:

    标签: r


    【解决方案1】:

    我会使用which.min

    which.min(abs(x-0.4))
    

    这将返回与0.4 最接近的数字的第一个索引。

    【讨论】:

      【解决方案2】:

      一种方式:

      # as mnel points out in his answer, the difference,
      # using `which` here gives all indices that match
      which(abs(x-0.4) == min(abs(x-0.4)))
      

      x 是你的向量。

      或者,

      # this one returns the first index, but is SLOW
      sort(abs(x-0.4), index.return=T)$ix[1]
      

      【讨论】:

        【解决方案3】:

        你也可以使用base::findInterval(0.4, x)

        【讨论】:

          猜你喜欢
          • 2014-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多