| arg_element | R Documentation |
Checks whether values in an argument are all elements of some set (arg_element()) or are not all elements of a set (arg_not_element()). arg_element() throws an error when all(is.element(x, values)) is FALSE, and arg_not_element() throws an error when any(is.element(x, values)) is TRUE.
arg_element(x, values, .arg = rlang::caller_arg(x), .msg = NULL, .call)
arg_not_element(x, values, .arg = rlang::caller_arg(x), .msg = NULL, .call)
x |
the argument to be checked |
values |
the values to check |
.arg |
the name of the argument supplied to |
.msg |
an optional alternative message to display if an error is thrown instead of the default message. |
.call |
the execution environment of a currently running function, e.g. |
arg_element() can be useful for checking whether an argument matches one or more allowed values. It's important that a check is done beforehand to ensure x is the correct type, e.g., using arg_string() or arg_character() if values is a character vector. No partial matching is used; the values must match exactly. Use match_arg() to allow partial matching and return the full version of the supplied argument.
arg_not_element() can be useful for ensuring there is no duplication of values between an argument and some other set.
Returns NULL invisibly if an error is not thrown.
is.element(), match_arg()
f <- function(z) {
arg_element(z, c("opt1", "opt2", "opt3"))
}
try(f("opt1")) # No error
try(f(c("opt1", "opt2"))) # No error, all are elements
try(f(c("opt1", "opt1"))) # No error: repeats allowed
try(f("bad_arg")) # Error: not an element of set
try(f("opt")) # Error: partial matching not allowed
try(f(c("opt1", "bad_arg"))) # Error: one non-match
g <- function(z) {
arg_not_element(z, c("bad1", "bad2", "bad3"))
}
try(g("bad1")) # Error: z is an element
try(g(c("bad1", "opt2"))) # Error: at least one bad match
try(g("opt1")) # No error: not an element
try(g(c("opt1", "opt2"))) # No error, none are elements
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.