首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >对stopifnot更好的错误信息?

对stopifnot更好的错误信息?
EN

Stack Overflow用户
提问于 2011-12-01 23:07:32
回答 7查看 17.1K关注 0票数 40

我使用的是stopifnot,我知道它只返回第一个非TRUE的值。如果这是一些奇怪的动态表达式,那么对自定义函数不熟悉的人就不能真正理解它。所以我很乐意添加一个自定义的错误消息。有什么建议吗?

代码语言:javascript
复制
Error: length(unique(nchar(check))) == 1 is not TRUE

基本上说明向量check的元素不具有相同的长度。有没有一种方式可以说:Error: Elements of your input vector do not have the same length!

EN

回答 7

Stack Overflow用户

发布于 2014-12-08 19:57:05

assertiveassertthat包具有更具可读性的检查函数。

代码语言:javascript
复制
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.
票数 12
EN

Stack Overflow用户

发布于 2021-03-07 04:01:49

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

代码语言:javascript
复制
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!
票数 8
EN

Stack Overflow用户

发布于 2017-06-27 20:33:40

stopifnot嵌入到tryCatch中,然后使用自定义消息使用stop重新转换异常,会怎么样呢?

类似于:

代码语言:javascript
复制
tryCatch(stopifnot(...,error=stop("Your customized error message"))

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

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8343509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档