问题
In one comment to the accepted answer on how to "correctly" specify optional arguments in R, @LouisMaddox said
missing()
is useless when you want to use proper checking of supplied parameters against a list though. For a functionFoo
with parameterbar
and optional switcha_or_b
(default value "a") you can writeFoo <- function(bar, a_or_b=c("a", "b"))
...
Is there a proper/recommended/idiomatic way for checking supplied parameters against a list of possible values?
I tried to look at graphics::plot.default
and also glimpsed at graphics::par
but couldn't make anything intelligible from these two functions (to see how the type
parameter is handled for example).
In the case of the type
parameter for example, all possible values are one-letter strings, so I guess somewhere, there's a big switch
statement or a bunch of if
statements.
回答1:
If you have a small number of options then use match.arg
within the function. See ?match.arg
for an example.
If the valid argument is all one letter strings then you will need to another approach such as:
# returns logical
is_one_letter_string <- function(x) {
!missing(x) && length(x) == 1 && is.character(x) && x %in% c(letters, LETTERS)
}
来源:https://stackoverflow.com/questions/41324398/r-proper-checking-of-supplied-parameters-against-a-list-of-values