Is there a function that checks if a certain value is contained within a certain range?

3

Assuming that:

x=120,00
limites.inferior<-80
limites.superior<-160
limites<-c(limites.inferior,limites.superior)

I'm doing this with a logical test:

x.int<-x>=limites[1] && x<=limites[2]

Is there a function that performs this simple verification?

    
asked by anonymous 15.03.2016 / 04:02

2 answers

4

You can get the same result by making a comparison less. As explained in the OS response .

  

The trick is to substract the middle between low and high from x, and then check whether that difference is less than half of the distance between low and high.

Translated into something like: The trick is to subtract half the sum of the lower limit and the upper limit of the number, and then check if the difference is less than half the distance between the lower limit and the upper limit.

In code you can have the following function:

in.interval2 <- function(numero, li, ls){
  abs(numero-(ls+li)/2) < (ls-li)/2 
}

> in.interval2(120, 80, 160)
[1] TRUE

In a matter of time, comparing with your function:

in.interval <- function(numero, li, ls){
  numero > li & numero < ls
}

> microbenchmark::microbenchmark(
+   in.interval(120, 80, 160),
+   in.interval2(120, 80, 160)
+ )
Unit: nanoseconds
                       expr  min   lq    mean median   uq   max neval cld
  in.interval(120, 80, 160)  708  709 1405.89   1062 1063 25836   100   a
 in.interval2(120, 80, 160) 1062 1416 2517.19   1417 1770 60872   100   a

And for slightly larger vectors.

> microbenchmark::microbenchmark(
+   in.interval(1:200, 80, 160),
+   in.interval2(1:200, 80, 160)
+ )
Unit: microseconds
                         expr   min    lq    mean median     uq    max neval cld
  in.interval(1:200, 80, 160) 6.725 7.079 8.20441  7.433 7.6095 33.268   100   b
 in.interval2(1:200, 80, 160) 3.186 3.540 4.49548  3.540 3.8940 20.528   100  a 

Note that this way you are 30% faster to compare a number and 100% faster to compare 200 numbers.

In terms of time, I do not think this will greatly speed up your code, since the unit is microseconds (10 ^ -6s) for the 200 vector. That is, you have to run this line at least a few 300,000 times for this change to accelerate for at least 1s.

    
15.03.2016 / 19:55
2

The closest I found was the findInterval function.

You can try something like:

x.int <- (findInterval(x, limites, rightmost.closed = TRUE) == 1)

But I honestly see no reason for you to stop using the test you are currently using.

    
15.03.2016 / 16:16