21

我想有一个中缀运算符%between%-R检查是否x在下限l和上限之间u

我创建了以下简单函数——但它不是中缀操作。

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

我的目标是将其替换为:x %between% c(l, u)

是否可以定义新的中缀操作?如果是这样,如何做到这一点?

提前致谢

4

3 回答 3

25

您可以将中缀运算符定义为函数:

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

正如@flodel 所指出的,这个运算符是矢量化的:

1:5 %between% c(1.5,3.5)
# [1] FALSE  TRUE  TRUE FALSE FALSE
于 2013-10-18T03:33:16.667 回答
12

该函数存在于包中data.table(略有不同,包括边界),实现为:

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)

它可以用作between(x,lower,upper)x %between% c(lower, upper)

于 2013-10-18T03:38:50.433 回答
4

为避免歧义,可以定义两个函数:

"%><%"  <- 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

甚至添加另外两个:

"%> =<%"<-function(x,rng) x > rng[1]  & x <= rng[2]
"%>= <%"<-function(x,rng) x >= rng[1] & x < rng[2]
于 2017-08-16T12:57:39.180 回答