Skip to contents

check_vector() and check_is_vector() are functions that check whether an input object is a valid vector (of a specified length, numeric or character type). The check_vector() function raises an error if the input does not meet the specified conditions. The check_is_vector() returns TRUE if the input is a valid vector according to the conditions and FALSE otherwise.

Usage

check_vector(
  vec,
  n = NULL,
  is_numeric = TRUE,
  inequality = c("==", ">", ">=", "<", "<="),
  allow_scalar = FALSE,
  par_name = "vec"
)

check_is_vector(
  vec,
  n = NULL,
  is_numeric = TRUE,
  inequality = c("==", ">", ">=", "<", "<="),
  allow_scalar = FALSE
)

Arguments

vec

The object to check.

n

An optional numeric value specifying the expected length of the vector. Default is NULL.

is_numeric

Logical, indicating if the vector should be numeric. Default is TRUE.

inequality

A string specifying the inequality condition to check for the length of the vector. Options are "==", ">", ">=", "<", "<=". Default is "==".

allow_scalar

Boolean, indicating if scalar values are allowed. Default is FALSE.

par_name

The name of the parameter to display in error messages.

Value

  • check_vector(): Returns the original vec if it meets the specified conditions. Raises an error otherwise.

  • check_is_vector(): Returns TRUE if vec is a valid vector according to the specified conditions, and FALSE otherwise.

Examples

# Examples for check_vector()
# ---------------------------
v <- c(1, 2, 3)
check_vector(v)
#> [1] 1 2 3

v2 <- c("a", "b", "c", "d")
check_vector(v2, is_numeric = FALSE)
#> [1] "a" "b" "c" "d"

v3 <- c("a", "b", "c", "d")
try(check_vector(v3, n = 5, is_numeric = FALSE))
#> Error in check_vector(v3, n = 5, is_numeric = FALSE) : 
#>   Expected 'vec' to have exactly 5 elements but got 4 elements

k <- 5
try(check_vector(k))
#> Error in check_vector(k) : 
#>   Expected 'vec' to be a vector with at least 2 elements but got a scalar

# Examples for check_is_vector()
# ------------------------------
check_is_vector(v)
#> [1] TRUE
check_is_vector(v2, is_numeric = FALSE)
#> [1] TRUE
check_is_vector(v3, n = 5, is_numeric = FALSE)
#> [1] FALSE
check_is_vector(k)
#> [1] FALSE