Description Usage Arguments Details Value Examples
Function match_arg()
is a safer, more flexible alternative
to match.arg().
It expects scalar values only.
It only works when called by another function.
A default value can be explicitly defined as such.
In case of no match, the error message is customizable, and prettier by default.
1 |
arg |
The argument to match. It is passed to pmatch() and is eventually converted to a character vector by this function. |
error |
Passed to |
... |
Further calls passed to |
..force_empty_stack |
Never ever use that argument. This is a flag only relevant when
debugging and testing |
When customizing error messages via error
and/or ...
, you
must ensure that any expression(s) embedded into these error messages
are properly evaluated in their own scope before being passed down to
match_arg()
. Else, you will get an error. See examples.
An atomic(1)
. Its type matches types of arg
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | ## It always fails when called outside of another function.
## Not run: match_arg()
## It matches the usual behavior of match.arg().
wrap <- function(foo = c("a", "b", "c")) {
return(match_arg(foo))
}
identical(wrap(), "a")
identical(wrap("b"), "b")
## Error messages are much more beautiful and match dotprofile's styling.
## Not run: wrap("d")
## You can explicitly mark a value as being the default one.
wrap2 <- function(foo = c("a", "b", default = "c")) {
return(match_arg(foo))
}
identical(wrap2(), "c")
identical(wrap2("b"), "b")
## Customize error messages.
wrap3 <- function(foo = c("a", "b", default = "c")) {
error <- cli::format_inline("{.arg {foo}} contains an error.")
return(
match_arg(foo, error,
ui_todo("It must be equal to a valid value.")))
}
## Not run: wrap3("d")
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.