R根据值列表正确检查提供的参数? [英] R Proper checking of supplied parameters against a list of values?

查看:118
本文介绍了R根据值列表正确检查提供的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关如何正确指定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 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.

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆