The index of the return from the vector of the value closest to this element

I have a list of items like

A= 0.992688 0.892195 0.889151 0.380672 0.180576 0.685028 0.58195 

Given an input element, e.g. 0.4, how can I find an index that contains the number closest to that number. For example, A[4] = 0.380672 is closest to 0.4. Therefore he must return to 4

+4
source share
3 answers

one way:

 # 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))) 

where x is your vector.

On the other hand,

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

I would use which.min

 which.min(abs(x-0.4)) 

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

+6
source

You can also use base::findInterval(0.4, x)

0
source

All Articles