I have the sorted vector
m<-c(1.1, 3.2, 3.6, 4, 4.6, 4.6, 5.6, 5.7, 6.2, 8.9)
I want to find the position of a value based on approximate matching. If the value does not exist in the vector i would like the position of the immediately previous value
for exact matching I would use
> match(4,m)
[1] 4
But if I do
> match(6,m)
[1] NA
What i would like to get in this example is 8
(the position of the immidiately previous value of 6 which is the position of 5.7 which is 8)
Thank you in advance
There is a built-in function that does precisely what you want: findInterval
...It's vectorized as well, so you can give it several values to find in one go which is much more efficient.
m <- c(1.1, 3.2, 3.6, 4, 4.6, 4.6, 5.6, 5.7, 6.2, 8.9)
# Find nearest (lower) index for both 4 and 6
findInterval(c(4,6), m)
# [1] 4 8
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