如何解决覆盖来自 R 中其他包的错误消息
我想在 R 中创建自己的错误消息以覆盖来自另一个包的错误消息。下面是一个简单的reprex:
myfunc <- function(x,y,string=TRUE){
if(string){
x+y
}else{
print("not numeric")
}
}
myfunc(2,"yes")
返回:
Error in x + y : non-numeric argument to binary operator
我想用我自己的特定于我的包的错误消息覆盖 Error in x + y : non-numeric argument to binary operator
,例如 Did you forget to use string=TRUE?
。我已经在函数中实现了 tryCatch
和 grepl
,并且它有效,但我不确定这是否是最好的方法:
myfunc <- function(x,string=TRUE){
tryCatch(myfunc(x,y),error=function(err){
if (grepl("non-numeric",err$message)) {
stop("Did you forget to use string=TRUE?")
}
})
if(string){
x+y
}else{
print("not numeric")
}
}
myfunc(2,"yes")
返回:
Error in value[[3L]](cond) : Did you forget to use string=TRUE?
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Called from: value[[3L]](cond)
这就是我想要的,虽然我更希望它没有说 Error in value[[3L]](cond)
。有没有办法摆脱它?另外,这是覆盖错误消息的最佳方法,还是有其他更好的方法?
解决方法
可以用 stop
代替 message
吗?
myfunc <- function(x,y,string=FALSE){
if(!string){
tryCatch(x+y,error = function(err) {
if (grepl("non-numeric",err$message)) {
message("Error : Did you forget to use string=TRUE?")
}
})
}else{
print("not numeric")
}
}
myfunc(2,"yes")
#Error : Did you forget to use string=TRUE?
myfunc(2,4)
#[1] 6
myfunc(2,"yes",string = TRUE)
#[1] "not numeric"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。