return index from a vector of the value closest to a given element

I have a list of elements such as

A=
  0.992688
  0.892195
  0.889151
  0.380672
  0.180576
  0.685028
  0.58195

Given an input element, like 0.4, how can I find the index that holds the number being most near to this number. For instance, A[4] = 0.380672 is most near to 0.4. Therefore, it should return to 4


Solution 1:

I would use which.min

which.min(abs(x-0.4))

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

Solution 2:

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.

Alternately,

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

Solution 3:

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