R根据值列表正确检查提供的参数? [英] R Proper checking of supplied parameters against a list of values?
问题描述
在有关如何正确指定R中的可选参数的接受答案中,@LouisMaddox表示
missing()
在您想要对提供的参数进行正确检查时没有用处尽管如此。对于带参数bar
和可选开关a_or_b
的函数Foo
(默认值a),您可以编写Foo < - 函数(bar,a_or_b = c(a,b))
...
是否有适当/推荐/惯用的方式来检查提供的参数与可能值列表?
我试着看看 graphics :: plot.default
,并在 graphics :: par
但是无法从这两个函数中理解任何东西(例如,如何处理类型
参数)。
<例如,在
类型
参数的情况下,所有可能的值都是单字母字符串,所以我猜在某处,有一个大的开关
语句或一堆 if
语句。 >功能内。例如,参见?match.arg
。 如果有效参数是全部一个字母字符串,那么您将需要另一种方法,如:
<$ p $ (x){
!missing(x)&& amp; amp;<长度(x)== 1&& is.character(x)&& x%in%c(letters,LETTERS)
}
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.
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)
}
这篇关于R根据值列表正确检查提供的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!