R 根据值列表正确检查提供的参数? [英] R Proper checking of supplied parameters against a list of values?
问题描述
在对 关于如何在 R 中正确"指定可选参数的公认答案 的一个评论中,@LouisMaddox 说
In one comment to the accepted answer on how to "correctly" specify optional arguments in R, @LouisMaddox said
missing()
但是当您想根据列表对提供的参数进行正确检查时,它是无用的.对于带有参数 bar
和可选开关 a_or_b
(默认值a")的函数 Foo
,您可以编写 Foo <- function(bar, a_or_b=c("a", "b"))
...
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?
我试图查看 graphics::plot.default
并瞥见了 graphics::par
但这两个函数无法理解(查看例如,如何处理 type
参数).
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).
以 type
参数为例,所有可能的值都是一个字母的字符串,所以我猜在某处,有一个很大的 switch
语句或一堆if
语句.
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.
推荐答案
如果您有少量选项,请在函数内使用 match.arg
.有关示例,请参见 ?match.arg
.
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屋!