Examples for 'rlang::arg_match'


Match an argument to a character vector

Aliases: arg_match arg_match0

Keywords:

### ** Examples

fn <- function(x = c("foo", "bar")) arg_match(x)
fn("bar")
[1] "bar"
# Throws an informative error for mismatches:
try(fn("b"))
Error in fn("b") : `x` must be one of "foo" or "bar", not "b".
ℹ Did you mean "bar"?
try(fn("baz"))
Error in fn("baz") : `x` must be one of "foo" or "bar", not "baz".
ℹ Did you mean "bar"?
# Use the bare-bones version with explicit values for speed:
arg_match0("bar", c("foo", "bar", "baz"))
[1] "bar"
# For convenience:
fn1 <- function(x = c("bar", "baz", "foo")) fn3(x)
fn2 <- function(x = c("baz", "bar", "foo")) fn3(x)
fn3 <- function(x) arg_match0(x, c("foo", "bar", "baz"))
fn1()
[1] "bar"
fn2("bar")
[1] "bar"
try(fn3("zoo"))
Error in fn3("zoo") : 
  `x` must be one of "foo", "bar", or "baz", not "zoo".
ℹ Did you mean "foo"?

[Package rlang version 1.1.4 Index]