Learn R Programming

inspector (version 1.0.3)

inspect_character_match: Validate character values

Description

inspect_character_match checks if an object is a character vector of length 1 that belongs to a set of allowed values. This can be useful to validate inputs in user-defined functions.

Usage

inspect_character_match(x, allowed, case_sensitive = FALSE)

Arguments

x

An arbitrary object.

allowed

A character vector.

case_sensitive

A non-missing logical value.

Value

inspect_character_match does not return any output. There are two possible outcomes:

  • The call is silent if x is a character vector of length 1 whose value belongs to the set of allowed values.

  • An informative error message is thrown otherwise.

Details

inspect_character_match conducts a series of tests to check if x is a character vector of length 1 whose value belongs to the set of allowed values. Namely, inspect_character_match checks if:

  • x is NULL or empty.

  • x is an atomic vector of length 1.

  • The typeof x is character.

  • x is NA or NaN.

  • x is one of the allowed values (as specified in the allowed argument).

By default, the comparison of x with allowed is not case sensitive. If you only want case sensitive matches of x to allowed set case_sensitive to TRUE.

See Also

Examples

Run this code
# NOT RUN {
# Calls that pass silently:
x1 <- "Kass"
x2 <- "kass"
inspect_character_match(x1, allowed = c("Kass", "Raftery"))
inspect_character_match(x2, allowed = c("Kass", "Raftery"))

# Calls that throw informative error messages:
y1 <- "kasss"
y2 <- "kass"
try(inspect_character_match(y1, allowed = c("Kass", "Raftery")))
try(inspect_character_match(y2,
  allowed = c("Kass", "Raftery"),
  case_sensitive = TRUE
))
mylist <- list(
  NULL, character(0), c("abc", "abcd"),
  c("abc", "abc"), "ab", list("abc"), factor("abc"), NaN, NA
)
try(inspect_character_match(mylist[[1]], "abc"))
try(inspect_character_match(mylist[[2]], "abc"))
try(inspect_character_match(mylist[[3]], "abc"))
try(inspect_character_match(mylist[[4]], "abc"))
try(inspect_character_match(mylist[[5]], "abc"))
try(inspect_character_match(mylist[[6]], "abc"))
try(inspect_character_match(mylist[[7]], "abc"))
try(inspect_character_match(mylist[[8]], "abc"))
try(inspect_character_match(mylist[[9]], "abc"))
# }

Run the code above in your browser using DataLab