# Enjoy R: is my x included in these bounds?

How many times have you written code like the following?

` if(x > lower_bound & x < upper_bound) return(T) `

` return(F)`

Throughout my coding experience so far, I’ve faced that a lot. And everytime this happened, I started thinking that I was not really writing it in the same way as I would have written it using basic maths on paper. As far as I know, R does not support the usual statement ` lower_bound < x < upper_bound `

. Therefore, I tried to implement it and I ended up with something working, which is nice.

I used ` %<% `

for “less than”, and ` %<=% `

for “less than or equal to”. Following the code:

``%<%` <- function(x, b) { `

` `

` useNames <- T `

` if(is.logical(x)) { `

` if(x) { `

` x <- as.numeric(names(x)) `

` useNames <- F `

` } else return(F) `

` } `

` `

` out <- T `

` if(x >= b) { `

` out <- F `

` } `

` if(useNames) names(out) <- b `

` out `

`} `

``%<=%` <- function(x, b) { `

` `

` useNames <- T `

` if(is.logical(x)) { `

` if(x) { `

` x <- as.numeric(names(x)) `

` useNames <- F `

` } else return(F) `

` } `

` `

` out <- T `

` if(x > b) { `

` out <- F `

` } `

` if(useNames) names(out) <- b `

` out `

`}`

Now, let’s play a little bit:

- Is 1 < 2 < 3? (Should return TRUE)

`1 %<% 2 %<% 3`

`[1] TRUE`

- Is 2 < 2 < 3? (Should return FALSE)

`2 %<% 2 %<% 3`

`[1] FALSE`

- Is 2 ≤ 2 < 3? (Should return TRUE)

`2 %<=% 2 %<% 3`

`[1] TRUE`

- Is 1 < 2 ≤ 2? (Should return TRUE)

`1 %<% 2 %<=% 2`

`[1] TRUE`

- Is 2 ≤ 2 ≤ 2? (Should return TRUE)

`2 %<=% 2 %<=% 2`

`[1] TRUE`

- Is 4 < 2 ≤ 5? (Should return FALSE)

`4 %<% 2 %<=% 5`

`[1] FALSE`

- Posted in: R ♦ rstats ♦ statistical software
- Tagged: arithmetic operators, r, rstats, statistical software

## Recent Comments