R Proper checking of supplied parameters against a list of values?

297 views Asked by At

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 function Foo with parameter bar and optional switch a_or_b (default value "a") you can write Foo <- 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

There are 1 answers

2
G. Grothendieck On BEST ANSWER

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)
}