tidyverse / magrittr

Improve the readability of R code with the pipe
https://magrittr.tidyverse.org
Other
961 stars 157 forks source link

Feature request: ``is_between()`` function #126

Closed kendonB closed 6 years ago

kendonB commented 8 years ago

x %>% is_between(4, 9) would be equivalent to: x < 9 & x > 4

x %>% is_weakly_between(4, 9) would be equivalent to: x <= 9 & x >= 4

smbache commented 8 years ago

I'll leave this open, but we're considering (althouh it's been a slow process) to move aliases to a separate package. Furthermore this is not really an alias. That said, I did want it a few times myself.

ondrejivanic commented 7 years ago

IMHO, is_between() should be inclusive. For example, between operator in SQL and dplyr::between include endpoints.

Deleetdk commented 7 years ago

I wrote a such function for my own package because it's so useful.

#' Check whether numbers are between two other numbers.
#'
#' Returns a logical vector of the same length as x. Can use inclusive or exclusive limits.
#' @param x (numeric vector) A vector of values to test.
#' @param a (numeric scalar) The lower limit.
#' @param b (numeric scalar) The upper limit.
#' @param include_lower (boolean) Whether to include the lower limit itself. Defaults to TRUE.
#' @param include_upper (boolean) Whether to include the upper limit itself. Defaults to TRUE.
#' @export
#' @examples
#' is_between(1:10, 3, 6)
is_between = function(x, a, b, include_lower = TRUE, include_upper = TRUE) {
  if (include_lower && include_upper) return(x >= a & x <= b)
  if (include_lower && !include_upper) return(x >= a & x < b)
  if (!include_lower && include_upper) return(x > a & x <= b)
  if (!include_lower && !include_upper) return(x > a & x < b)
}
hadley commented 6 years ago

See dplyr::between() which will eventually be extracted out into a lower-dependency package.