quickest R implementation of within
operators, optimization, r
Solution
"%within[]%" <- function(x,y){x>=y[1] & x<=y[2]}
x <- 1:10
y <- c(3,5)
x %within[]% y
"%within[]2%" <- function(x,y) findInterval(x,y,rightmost.closed=TRUE)==1
x %within[]2% y
library(microbenchmark)
microbenchmark(x %within[]% y,x %within[]2% y)
Unit: microseconds
expr min lq median uq max
1 x %within[]% y 1.849 2.465 2.6185 2.773 11.395
2 x %within[]2% y 4.928 5.544 5.8520 6.160 37.265
x <- 1:1e6
microbenchmark(x %within[]% y,x %within[]2% y)
Unit: milliseconds
expr min lq median uq max
1 x %within[]% y 27.81535 29.60647 31.25193 56.68517 88.16961
2 x %within[]2% y 20.75496 23.07100 24.37369 43.15691 69.62122
This probably is a job for Rcpp.
Problem
I use `"%within[]%" <- function(x,y){x>=y[1] & x<=y[2]}` (meaning `x` is in the compact set `y`) a lot in R code but I am pretty sure It is awfully slow. Do you have something quicker ? It needs to work for everything where `>` is defined. EDIT: `x` could be a vector and `y` a 2 elments vector in ascending order... EDIT2: It is strange that nobody (to my knowledge) wrote a package `rOperator` implementing quick `C` operators like `%w/i[]%, %w/i[[%, ...` EDIT3: I realized that my question was too general as making assumption on `x,y` would modify any result, I think we should close it, thanks for your input.