ricardo ricardo - 2 years ago 78
R Question

creating an infix %between% operator in R

I would like to have an infix operator

%between%
in
R
-- to check to see if
x
is between lower bound
l
and upper bound
u
.

I have created the following simple function -- but it's not an infix operation.

# between function - check to see if x is between l and u
is.between <- function(x, l, u) { x > l & x < u }


My aim is to replace this with:
x %between% c(l, u)


Is it possible to define new infix operations? If so, how does one do this?

thanks in advance

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download