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
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.
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.
I would use which.min
which.min(abs(x-0.4))
This will return the first index of the closest number to 0.4
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With