gpt4 book ai didi

r - 如何处理......当最后一个参数为空时?

转载 作者:行者123 更新时间:2023-12-03 18:25:09 25 4
gpt4 key购买 nike

使用时 ...捕获其他参数,将最后一个参数留空并尝试使用 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

现在它变得很不清楚出了什么问题。是否有惯用的技术来捕获错误并用有用的消息报告它?

最佳答案

f <- function(x, ...) {
return(
as.list(substitute(list(...)))[-1]
)
}

err <- f(x = 0, y = 10,) #have a closer look --> str(err)

#$`y`
#[1] 10
#
#[[2]]

fine<- f(x = 0, y = 10)

#$`y`
#[1] 10

您会在 Error 案例中看到您有一个空的符号列表元素。我相信您可以将此信息用作错误处理的 Hook 。

所以你有意义的错误处理可以是这样的:

感谢@Roland 的加入。
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.

关于r - 如何处理......当最后一个参数为空时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52091023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com