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
This function can be used as infix operator a %divisible% b or as a function call `%divisible%`(a, b) . Both are the same. Things to remember while defining your own infix operators are that they must start and end with % . Surround it with back tick ( ` ) in the function definition and escape any special symbols.
infix operator (plural infix operators) (computing) an operator that is placed in between the operands like it is commonly used in arithmetical and logical formulae and statements. The plus sign in "2 + 2" is placed as an infix operator in arithmetic.
What are infix functions? In R, most of the functions are “prefix” - meaning that the function name comes before the arguments, which are put between parentheses : fun(a,b) . With infix functions, the name comes between the arguments a fun b . In fact, you use this type on a daily basis with : , + , and so on.
Functions in Haskell default to prefix syntax, meaning that the function being applied is at the beginning of the expression rather than the middle. Operators are functions which can be used in infix style.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With