我有一个元素列表,例如
A=
0.992688
0.892195
0.889151
0.380672
0.180576
0.685028
0.58195
给定一个输入元素(如0.4),我如何找到使该数字最接近该数字的索引。例如,
A[4] = 0.380672
最接近0.4。因此,它应该返回到4
最佳答案
单程:
# 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]
关于从最接近给定元素的值的向量返回索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14968954/