我希望能够在调用R函数时检查所有未指定默认值的参数是否已经指定。这对我来说似乎是一个明智的做法,因为它避免了在发现缺少一个值后(这可能会在很多处理之后)函数失败的情况。
一种实现此任务的方法是为每个参数编写一个if (missing(arg))语句,但这需要保持函数参数和上述语句的一致性,因此我正在寻找更好的解决方案。
目前我使用以下函数,在大多数情况下可以工作,但不是全部情况。
一种实现此任务的方法是为每个参数编写一个if (missing(arg))语句,但这需要保持函数参数和上述语句的一致性,因此我正在寻找更好的解决方案。
目前我使用以下函数,在大多数情况下可以工作,但不是全部情况。
# check for required arguments by getting arguments for the
# definition of the calling function and comparing to the arguments
# in the function call
check_required_args <- function () {
def <- sys.function(-1)
f_args <- formals(def)
f_args <- f_args[sapply(f_args, is.name)] # remove arguments with defaults
f_args <- names(f_args)
f_args <- f_args[f_args != '...'] # remove ellipsis argument if present
call <- match.call(definition=def, call=sys.call(-1))
f_name <- call[1]
c_args <- names(as.list(call[-1]))
for(n in f_args) {
if (!n %in% c_args) {
stop("Argument '", n, "' missing from call to function ",
f_name, "()", call.=FALSE)
}
}
}
f <- function(a, b, c=2) check_required_args()
f(a=1) # should fail (missing argument b)
f(2, 3) # should work
f(2, c=5) # should fail (missing argument b)
f(2, 3, 4) # should work
f <- function(a, b, ...) f2(a, b, ...)
f2 <- function(a, b, c, ...) check_required_args()
f2(a=1, b=2, c=3) # should work
f2(a=1, b=2) # should fail (missing argument c for function f2)
f(a=1, b=2, c=3) # should work
f(a=1, b=2) # should fail (missing argument c for function f2)
这个函数能否改进,以使其在所有情况下都能工作?如果不能,是否有更适合执行此检查的解决方案?
R
的惰性求值机制非常棒,因为不需要的参数可以被忽略。更何况,你首先将参数放入函数的形式参数中的原因就是要使用它们!所以,对于你的问题,正确的答案是:不,这不是一个“明智”的做法。 - Carl Witthoft列表
变量中。其次,在某个时候,你必须进行输入验证,不仅要验证其存在性,还要验证其正确的数据类型(例如,字符 vs. 数值)。 - Carl Witthoft