Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an infix %between% operator?

Tags:

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

like image 634
ricardo Avatar asked Oct 18 '13 03:10

ricardo


People also ask

How do you write an infix operator?

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.

What is operator in infix?

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.

How do you define an infix function?

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.

What is an infix function in Haskell?

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.


2 Answers

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 
like image 58
mrip Avatar answered Oct 27 '22 18:10

mrip


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)

like image 21
mnel Avatar answered Oct 27 '22 18:10

mnel