Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

r - How can I create an infix %between% operator?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...