gpt4 book ai didi

r - 当表达式返回长度为零时,使R stopifnot或类似的简单函数引发错误

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

我在R中使用stopifnot函数来验证预期结果。但是,我注意到,如果表达式返回长度为0的 vector ,则stopifnot不会引发错误。这是一个简单的可复制示例。

想象一下一个优化函数,其中一个列表元素被命名为convergence包含0或1,并且我希望验证名为convergence的元素包含0并引发错误。

return01 <- function(x){
return(list(convergence = x))
}
opt1 <- return01(1)

我可以轻松使用 stopifnot进行所需的验证。
stopifnot(opt1$convergence == 0) # raises desired error

但是,假设我键入了错误的元素名称,例如 converged而不是 convergence。我的验证不再引发任何错误,因为 opt1$convergedNULL并且 opt1$converged == 0解析为 logical(0)
stopifnot(opt1$converged == 0) # does not raise an error
stopifnot(NULL == 0) # does not raise an error

我在下面提出了变通方法,在该变通方法中,我总是必须还要验证表达式的长度。
stopifnot(opt1$converged == 0, length(opt1$converged == 0) > 0) # raises an error
stopifnot(NULL == 0, length(NULL == 0) > 0) # raises an error

这里是否有一个更简单,更优雅或更佳的解决方案,以使此验证对返回 logical(0)的表达式具有鲁棒性,同时又保持 stopifnot(opt1$convergence == 0)的简洁性和简洁性,而不必使用 length显式地执行另一个表达式?具体来说,如果表达式返回 logical(0),我希望验证也引发错误。

最佳答案

检查它是否等于零:

stopifnot(identical(opt1$convergence, 0))

或者,如果收敛通常是整数类型,请使用 0L

如果收敛不是0,则上面的代码将引发错误。例如,
stopifnot(identical(1, 0))
## Error: identical(1, 0) is not TRUE

stopifnot(identical(NULL, 0))
## Error: identical(NULL, 0) is not TRUE

stopifnot(identical(numeric(0), 0)
## Error: identical(numeric(0), 0) is not TRUE

stopifnot(identical(logical(0), 0))
## Error: identical(logical(0), 0) is not TRUE

关于r - 当表达式返回长度为零时,使R stopifnot或类似的简单函数引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48124141/

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