user297850
user297850

Reputation: 8005

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

Upvotes: 9

Views: 5795

Answers (3)

psychonomics
psychonomics

Reputation: 774

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

Upvotes: 5

Arun
Arun

Reputation: 118779

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]

Upvotes: 9

mnel
mnel

Reputation: 115382

I would use which.min

which.min(abs(x-0.4))

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

Upvotes: 14

Related Questions