更好的错误消息为stopifnot?

Mat*_*ert 29 r

我正在使用stopifnot,我理解它只返回第一个不是的值TRUE.我是一个怪异的动态表达,没有进入自定义功能的人无法真正做出一些东西.所以我很乐意添加自定义错误消息.有什么建议?

Error: length(unique(nchar(check))) == 1 is not TRUE
Run Code Online (Sandbox Code Playgroud)

基本上说明向量的元素check不具有相同的长度.有没有办法说:Error: Elements of your input vector do not have the same length!

小智 36

自定义消息可以作为标签添加到您的表达式中:

stopifnot("Elements of your input vector do not have the same length!" =
  length(unique(nchar(check))) == 1)

# Error: Elements of your input vector do not have the same length!
Run Code Online (Sandbox Code Playgroud)

  • 没关系,我看到它是作为 R 4.0.0 中的功能添加的。 (2认同)

And*_*rie 34

使用stopif声明:

if(length(unique(nchar(check))) != 1) 
  stop("Error: Elements of your input vector do not have the same length!")
Run Code Online (Sandbox Code Playgroud)

只要记住,stopifnot有说明负面的便利,所以你的条件if需要是你的停止条件的否定.


这是错误消息的样子:

> check = c("x", "xx", "xxx")
> if(length(unique(nchar(check))) != 1) 
+   stop("Error: Elements of your input vector do not have the same length!")

Error in eval(expr, envir, enclos) : 
  Error: Elements of your input vector do not have the same length!
Run Code Online (Sandbox Code Playgroud)

  • @ ran2"stopifnot"的用例正是您目前正在使用它的内容.这非常直观.但它不会产生漂亮的错误消息.正如他们用英语说的那样,课程用马. (3认同)
  • @ RAN2.`stopifnot`是检查输入上多个条件的快捷方法.所以例如,如果你可以说`stopifnot(A> 0,B <= 0,C == TRUE)`并确保当三个条件中的任何一个不满足时代码停止. (3认同)
  • 如果不是那么好的话会停止什么?我的意思是使用if是直观的解决方案.几乎所有语言都有,甚至是英语.是否有一些特定的用例用于止步? (2认同)

Ric*_*ton 12

assertiveassertthat包有更具可读性检查功能.

library(assertthat)
assert_that(length(unique(nchar(check))) == 1)
## Error: length(unique(nchar(check))) == 1 are not all true.

library(assertive)
assert_is_scalar(unique(nchar(check)))
## Error: unique(nchar(check)) does not have length one.

if(!is_scalar(unique(nchar(check)))) 
{
  stop("Elements of check have different numbers of characters.")
}
## Error: Elements of check have different numbers of characters.
Run Code Online (Sandbox Code Playgroud)


tom*_*mas 6

如何将异常嵌入stopifnottryCatch然后stop使用自定义消息重铸异常?

就像是:

tryCatch(stopifnot(...,error=stop("Your customized error message"))
Run Code Online (Sandbox Code Playgroud)

与其他一些解决方案不同,这不需要额外的包。与 usingif语句结合使用时,stop您保留了 的性能优势stopifnot,当您使用新的 R 版本时。由于 R 版本 3.5.0stopifnot按顺序计算表达式并在第一次失败时停止。

  • 应该是: tryCatch(stopifnot(...), error=function() stop(msg)) (3认同)

Max*_*ner 5

或者你可以打包它.

assert <- function (expr, error) {
  if (! expr) stop(error, call. = FALSE)
}
Run Code Online (Sandbox Code Playgroud)

所以你有了:

> check = c("x", "xx", "xxx")
> assert(length(unique(nchar(check))) == 1, "Elements of your input vector do not have the same length!")

Error: Elements of your input vector do not have the same length!
Run Code Online (Sandbox Code Playgroud)

  • 这是一个提供模仿 stopifnot() 消息的默认错误消息的版本。&lt;br/&gt;```assert &lt;- function (expr, msg) { if(missing(msg)) msg​​ &lt;- Paste("条件",deparse(as.list(match.call())$expr), " is not TRUE") if (! expr) stop(msg, call.= FALSE) }``` 因此,assert(is.character(2)) 返回 `Error: Condition is.character(dir) is not TRUE` (2认同)