[R] finding numbers in a range

David Winsemius dwinsemius at comcast.net
Wed Jun 1 23:40:54 CEST 2011


On Jun 1, 2011, at 5:07 PM, Salih Tuna wrote:

> Hi,
> Is there a quick way of finding if numbers in a vector falls in  
> between a
> range defined in another matrix.
> As an example let
> x   y
> 0      1   3
> 2      6   9
> 25    15  18
>
> I want to check one by one whether 0,2 and 25 falls in any of the  
> ranges in
> y.
> I am using 2 for loops but it is taking a huge amount of time.
> is there any other alternative way to do this?

If this represents the full complexity of the problem then  
findInterval would work:

 > findInterval(c(0,2,25), c(1,3,6,9,15,18) ) %in% c(1,3,5)
[1] FALSE  TRUE FALSE

On the other hand if the y intervals overlap then a different method  
may be needed.

 > sapply( c(0, 2, 25) , function(x) {any( y[,1] < x & x < y[,2]) })
[1] FALSE  TRUE FALSE

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list