8

我有一个元素列表,例如

A=
  0.992688
  0.892195
  0.889151
  0.380672
  0.180576
  0.685028
  0.58195

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

4

3 回答 3

14

I would use which.min

which.min(abs(x-0.4))

This will return the first index of the closest number to 0.4.

于 2013-02-19T22:48:19.987 回答
8

单程:

# 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]
于 2013-02-19T22:40:18.713 回答
3

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

于 2019-01-29T17:28:40.797 回答