Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position in vector based on approximate matching

Tags:

r

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

like image 980
ECII Avatar asked Aug 31 '11 07:08

ECII


1 Answers

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
like image 195
Tommy Avatar answered Oct 21 '22 18:10

Tommy