Skip to contents

Check if length(arg) is ==, <=, or >= length.

Usage

check_length_equals(arg, length, signal = "error", msg = NULL, call. = FALSE)

check_length_leq(arg, length, signal = "error", msg = NULL, call. = FALSE)

check_length_geq(arg, length, signal = "error", msg = NULL, call. = FALSE)

Arguments

arg

(object)
The argument to check.

length

(Scalar integer)
An integer for the length of arg.

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_length_*() examples
#----------------------------------------------------------------------------
library(bkcheck)

#----------------------------------------------------------------------------
# Length equals
#----------------------------------------------------------------------------
f <- function(x) {
  x |>
    check_length_equals(2L)
}

f(1:2)
try(f(1))
#> Error : The length of argument `x` must be 2.
#> 
#> length(x) = 1
#> 
#> Call: f(x = 1)

#----------------------------------------------------------------------------
# Length less than or equal to
#----------------------------------------------------------------------------
f <- function(x) {
  x |>
    check_length_leq(2L)
}

f(1:2)
try(f(1:3))
#> Error : The length of argument `x` must be at most 2.
#> 
#> length(x) = 3
#> 
#> Call: f(x = 1:3)

#----------------------------------------------------------------------------
# Length greater than or equal to
#----------------------------------------------------------------------------
f <- function(x) {
  x |>
    check_length_geq(3L)
}

f(1:3)
try(f(1:2))
#> Error : The length of argument `x` must be at least 3.
#> 
#> length(x) = 2
#> 
#> Call: f(x = 1:2)