Skip to contents

Check if all elements of arg lie within the interval bounded by lower and upper.

Usage

check_range(
  arg,
  lower,
  upper,
  lower_inclusive = TRUE,
  upper_inclusive = TRUE,
  signal = "error",
  msg = NULL,
  call. = FALSE
)

Arguments

arg

(Numeric)
The argument to check.

lower

(Scalar numeric)
The lower bound of the interval.

upper

(Scalar numeric)
The upper bound of the interval. Must be greater than or equal to lower.

lower_inclusive

(Scalar logical: TRUE)
Whether the lower bound is inclusive. TRUE makes the bound closed (arg >= lower). FALSE makes the bound open (arg > lower).

upper_inclusive

(Scalar logical: TRUE)
Whether the upper bound is inclusive. TRUE makes the bound closed (arg <= upper). FALSE makes the bound open (arg < upper).

signal

(string: c("error", "warning", "message"))
Must be one of "error", "warning", or "message". "error" (default) calls base::stop() to signal an error message. "warning" calls base::warning() to signal a warning message. "message" calls base::message() to signal a message.

msg

(string or NULL: NULL)
A string that replaces the default message. Set as NULL to use the default message.

call.

(Scalar logical: c(FALSE, TRUE))
Passed to stop() or warning(). The default msg includes it's own formatted call, hence call. should be FALSE (default). If you insert your own msg, then you may want call. = TRUE.

Value

invisible(arg) or condition determined by argument signal.

Examples

#----------------------------------------------------------------------------
# check_range() examples
#----------------------------------------------------------------------------
library(bkcheck)

#----------------------------------------------------------------------------
# Closed interval [0, 1]
#----------------------------------------------------------------------------
f <- function(x) {
  x |>
    check_numeric() |>
    check_range(0, 1)
}

f(c(0, 0.5, 1))
try(f(c(0, 0.5, 1.5)))
#> Error : Argument `x` must be in the interval [0, 1].
#> 
#> min(x, na.rm = TRUE) = 0
#> max(x, na.rm = TRUE) = 1.5
#> 
#> Call: f(x = c(0, 0.5, 1.5))

#----------------------------------------------------------------------------
# Open interval (0, 1)
#----------------------------------------------------------------------------
g <- function(x) {
  x |>
    check_numeric() |>
    check_range(0, 1, lower_inclusive = FALSE, upper_inclusive = FALSE)
}

g(c(0.25, 0.5, 0.75))
try(g(c(0, 0.5, 1)))
#> Error : Argument `x` must be in the interval (0, 1).
#> 
#> min(x, na.rm = TRUE) = 0
#> max(x, na.rm = TRUE) = 1
#> 
#> Call: g(x = c(0, 0.5, 1))