How can I create an infix %between% operator?

You can define infix operators as functions:

`%between%`<-function(x,rng) x>rng[1] & x<rng[2]
1 %between% c(0,3)
# [1] TRUE
1 %between% c(2,3)
# [1] FALSE

As pointed out by @flodel, this operator is vectorized:

1:5 %between% c(1.5,3.5)
# [1] FALSE  TRUE  TRUE FALSE FALSE

To avoid ambiguity, one could define two functions:

"%><%"  <- function(x, rng) x > rng[1]  & x < rng[2]
"%>=<%" <- function(x, rng) x >= rng[1] & x <= rng[2]
x=1:5
x %><% c(2,4)
[1] FALSE FALSE  TRUE FALSE FALSE
x %>=<% c(2,4)
[1] FALSE  TRUE  TRUE  TRUE FALSE

Or even add these two others:

"%> =<%"<-function(x,rng) x > rng[1]  & x <= rng[2]
"%>= <%"<-function(x,rng) x >= rng[1] & x < rng[2]

This function exists in the package data.table (with the slight difference that the bounds are included), implemented as:

between <- function(x,lower,upper,incbounds=TRUE)
{
  if(incbounds) x>=lower & x<=upper
  else x>lower & x<upper
}

"%between%" <- function(x,y) between(x,y[1],y[2],incbounds=TRUE)

It can be used as between(x,lower,upper) or x %between% c(lower, upper)

Tags:

R