Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

like image 776
user297850 Avatar asked Feb 19 '13 22:02

user297850


People also ask

How do you find the index of the closest value in a list Python?

We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value.

How do you return the index of an element in a vector in R?

Use the match() Function to Find the Index of an Element in R. The match() function is very similar to the which() function. It returns a vector with the first index (if the element is at more than one position as in our case) of the element and is considered faster than the which() function.


1 Answers

I would use which.min

which.min(abs(x-0.4))

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

like image 60
mnel Avatar answered Sep 19 '22 17:09

mnel