当最终参数为空时如何处理...

时间:2018-08-30 07:03:57

标签: r

使用...捕获其他参数时,将最后一个参数保留为空并尝试使用list(...)会产生错误

f <- function(x, ...) {
    args <- list(...)
}

f(x = 0, y = 10,)


> Error in f(x = 0, y = 10, ) : argument is missing, with no default

此错误消息仍然有用,但是如果您传递...,则会得到以下内容

f1 <- function(x, ...) {
    f2(x, ...)
}

f2 <- function(x, ...) {
    list(...)
}

f1(x = 0, y = 10,)

> Error in f2(x, ...) : argument is missing, with no default

现在非常不清楚出了什么问题。是否有惯用的技术来捕获错误并通过有用的消息进行报告?

1 个答案:

答案 0 :(得分:3)

f <- function(x, ...) {
    res <- as.list(substitute(list(...)))[-1]
    if( any(  sapply(res, function(x) { is.symbol(x) && deparse(x) == "" })  ) )  stop('Please remove the the last/tailing comma "," from your input arguments.')
    print("code can run. Hurraa")
}

a <- 0; 
f(x = 0, y = a, hehe = "", "")
#[1] "code can run. Hurraa"

f(x = 0, y = a, hehe = "", "", NULL)
#[1] "code can run. Hurraa"

f(x = 0, y = a, hehe = "", "",)
#Error in f(x = 0, y = a, hehe = "", "", ) : 
#Please remove the the last/tailing comma "," from your input arguments.

f(x = 0, y = a, hehe = "", "", NULL,)
#Error in f(x = 0, y = a, hehe = "", "", NULL, ) : 
#Please remove the the last/tailing comma "," from your input arguments.

在“错误”情况下,您看到一个空的符号列表元素。我相信您可以将这些信息用作错误处理的挂钩。


因此您有意义的错误处理如下所示:

感谢@Roland的加入。

get