我有一个元素列表,如
A=
0.992688
0.892195
0.889151
0.380672
0.180576
0.685028
0.58195
Run Code Online (Sandbox Code Playgroud)
给定一个输入元素,如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)))
Run Code Online (Sandbox Code Playgroud)
x你的向量在哪里
交替,
# this one returns the first index, but is SLOW
sort(abs(x-0.4), index.return=T)$ix[1]
Run Code Online (Sandbox Code Playgroud)