我正在使用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)
And*_*rie 34
使用stop
和if
声明:
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)
Ric*_*ton 12
在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.
Run Code Online (Sandbox Code Playgroud)
如何将异常嵌入stopifnot
到tryCatch
然后stop
使用自定义消息重铸异常?
就像是:
tryCatch(stopifnot(...,error=stop("Your customized error message"))
Run Code Online (Sandbox Code Playgroud)
与其他一些解决方案不同,这不需要额外的包。与 usingif
语句结合使用时,stop
您保留了 的性能优势stopifnot
,当您使用新的 R 版本时。由于 R 版本 3.5.0stopifnot
按顺序计算表达式并在第一次失败时停止。
或者你可以打包它.
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)