Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

arg_match

Match an argument to a character vector


Description

This is equivalent to base::match.arg() with a few differences:

  • Partial matches trigger an error.

  • Error messages are a bit more informative and obey the tidyverse standards.

arg_match() derives the possible values from the caller frame.

arg_match0() is a bare-bones version if performance is at a premium. It requires a string as arg and explicit values. For convenience, arg may also be a character vector containing every element of values, possibly permuted. In this case, the first element of arg is used.

Usage

arg_match(arg, values = NULL)

arg_match0(arg, values, arg_nm = as_label(substitute(arg)))

Arguments

arg

A symbol referring to an argument accepting strings.

values

The possible values that arg can take.

arg_nm

The label to be used for arg in error messages.

Value

The string supplied to arg.

Examples

fn <- function(x = c("foo", "bar")) arg_match(x)
fn("bar")

# Throws an informative error for mismatches:
try(fn("b"))
try(fn("baz"))

# Use the bare-bones version with explicit values for speed:
arg_match0("bar", c("foo", "bar", "baz"))

# 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()
fn2("bar")
try(fn3("zoo"))

rlang

Functions for Base Types and Core R and 'Tidyverse' Features

v0.4.11
MIT + file LICENSE
Authors
Lionel Henry [aut, cre], Hadley Wickham [aut], mikefc [cph] (Hash implementation based on Mike's xxhashlite), Yann Collet [cph] (Author of the embedded xxHash library), RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.