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

女生的网名这么多〃 提交于 2019-12-04 05:18:20

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!