Match arg against a series of candidate choices. arg matches an element of choices if arg is a prefix of that element.

str_match_arg(
  arg,
  choices = NULL,
  index = FALSE,
  several_ok = FALSE,
  ignore_case = FALSE
)

match_arg(
  arg,
  choices = NULL,
  index = FALSE,
  several_ok = FALSE,
  ignore_case = FALSE
)

Arguments

arg

A character vector (of length one unless several_ok = TRUE).

choices

A character vector of candidate values.

index

Return the index of the match rather than the match itself?

several_ok

Allow arg to have length greater than one to match several arguments at once?

ignore_case

Ignore case while matching. If this is TRUE, the returned value is the matched element of choices (with its original casing).

Details

ERRORs are thrown when a match is not made and where the match is ambiguous. However, sometimes ambiguities are inevitable. Consider the case where choices = c("ab", "abc"), then there's no way to choose "ab" because "ab" is a prefix for "ab" and "abc". If this is the case, you need to provide a full match, i.e. using arg = "ab" will get you "ab" without an error, however arg = "a" will throw an ambiguity error.

When choices is NULL, the choices are obtained from a default setting for the formal argument arg of the function from which str_match_arg was called. This is consistent with base::match.arg(). See the examples for details.

When arg and choices are identical and several_ok = FALSE, the first element of choices is returned. This is consistent with base::match.arg().

This function inspired by RSAGA::match.arg.ext(). Its behaviour is almost identical (the difference is that RSAGA::match.arg.ext(..., ignore.case = TRUE) always returns in all lower case; strex::match_arg(..., ignore_case = TRUE) ignores case while matching but returns the element of choices in its original case). RSAGA is a heavy package to depend upon so strex::match_arg() is handy for package developers.

This function is designed to be used inside of other functions. It's fine to use it for other purposes, but the error messages might be a bit weird.

Examples

choices <- c("Apples", "Pears", "Bananas", "Oranges")
match_arg("A", choices)
#> [1] "Apples"
match_arg("B", choices, index = TRUE)
#> [1] 3
match_arg(c("a", "b"), choices, several_ok = TRUE, ignore_case = TRUE)
#> [1] "Apples"  "Bananas"
match_arg(c("b", "a"), choices,
  ignore_case = TRUE, index = TRUE,
  several_ok = TRUE
)
#> [1] 3 1
myword <- function(w = c("abacus", "baseball", "candy")) {
  w <- match_arg(w)
  w
}
myword("b")
#> [1] "baseball"
myword()
#> [1] "abacus"
myword <- function(w = c("abacus", "baseball", "candy")) {
  w <- match_arg(w, several_ok = TRUE)
  w
}
myword("c")
#> [1] "candy"
myword()
#> [1] "abacus"   "baseball" "candy"