我使用的是stopifnot
,我知道它只返回第一个非TRUE
的值。如果这是一些奇怪的动态表达式,那么对自定义函数不熟悉的人就不能真正理解它。所以我很乐意添加一个自定义的错误消息。有什么建议吗?
Error: length(unique(nchar(check))) == 1 is not TRUE
基本上说明向量check
的元素不具有相同的长度。有没有一种方式可以说:Error: Elements of your input vector do not have the same length!
发布于 2014-12-08 19:57:05
assertive
和assertthat
包具有更具可读性的检查函数。
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.
发布于 2021-03-07 04:01:49
可以将自定义消息作为标签添加到表达式中:
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!
发布于 2017-06-27 20:33:40
将stopifnot
嵌入到tryCatch
中,然后使用自定义消息使用stop
重新转换异常,会怎么样呢?
类似于:
tryCatch(stopifnot(...,error=stop("Your customized error message"))
与其他一些解决方案不同,这不需要额外的包。与结合使用if
语句和stop
相比,当您使用新的R版本时,可以保留stopifnot
的性能优势。从R版本3.5.0开始,stopifnot
会按顺序计算表达式,并在第一次失败时停止。
https://stackoverflow.com/questions/8343509
复制相似问题