filesstrings (version 2.5.0)

match_arg: Argument Matching

Description

Match arg against a series of candidate choices where NULL means take the first one. arg matches an element of choices if arg is a prefix of that element.

Usage

match_arg(arg, choices, 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? Default no.

several_ok

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

ignore_case

Ignore case while matching. Default no. 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.

This function inspired by RSAGA::match.arg.ext(). Its behaviour is almost identical (the difference is that RSAGA::match.arg.ext(..., ignore.case = TRUE) guarantees that the function returns strings in all lower case, but that is not so with filesstrings::match_arg(..., ignore_case = TRUE)) but RSAGA is a heavy package to depend upon so filesstrings::match_arg() might be handy for package developers.

Examples

Run this code
# NOT RUN {
choices <- c("Apples", "Pears", "Bananas", "Oranges")
match_arg(NULL, choices)
match_arg("A", choices)
match_arg("B", choices, index = TRUE)
match_arg(c("a", "b"), choices, several_ok = TRUE, ignore_case = TRUE)
match_arg(c("b", "a"), choices, ignore_case = TRUE, index = TRUE,
          several_ok = TRUE)

# }

Run the code above in your browser using DataLab