How can I create an infix

后端 未结 3 1546
耶瑟儿~
耶瑟儿~ 2020-12-09 17:01

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

相关标签:
3条回答
  • 2020-12-09 17:04

    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
    
    0 讨论(0)
  • 2020-12-09 17:14

    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)

    0 讨论(0)
  • 2020-12-09 17:24

    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]
    
    0 讨论(0)
提交回复
热议问题