R函数返回值以及警告消息 [英] R function return value as well warning message
问题描述
我调用了其他的lib函数,它进行计算并抛出警告消息。我尝试使用tryCatch()来捕获消息,但不知道如何保留计算值和警告消息。这里是示例(简化)代码,我希望mydiv函数具有计算值和警告消息。现在mydiv调用将返回除法值或警告,但不是两者。
I called other lib function, which does the calculation and throws warning message. I tried to use tryCatch() to capture the message but do not know how to keep the calculated value and the warning message. Here is sample (simplified) code, I would like mydiv function has both calculated value and warning message. Right now mydiv calls will return the division value or the warning but not both.
mydiv = function(x, y){
tryCatch({
# raise warning message
if (x > y)
warning("throw a warning")
# function calc result
x/y
},
warning = function(war) {
flag = paste("DIV Warning:", war$message)
return (flag)
},
error = function(err) {
flag = paste("DIV Err", err)
return (flag)
})
}
如果我调用x = mydiv(2,1),那么x的值为DIV Warning:throw a warning;如果x = mydiv(2,4),则x:[1] 0.5。
所以我的问题是:1.使用tryCatch:如果可能的话如何返回计算的值和警告消息; 2.是否有更好的方法从函数中获取这两个值。
If I call x = mydiv(2, 1) then the x has value "DIV Warning: throw a warning"; if x = mydiv(2, 4) then x: [1] 0.5. So my question is: 1. use tryCatch: how to return the calculated value and warning message if possible; 2. whether there is a better approach to get both values from a function.
推荐答案
您可以使用内置的警告函数作为如下:
You could use the built in warning function as in the following:
mydiv = function(x, y){
if (x > y)
warning("throw a warning")
# function calc result
return(x/y)
}
如果您想要返回警告而不是将其作为警告消息发出,则可以返回一个指定列表,如果未生成警告,则列表中的警告条目将为NA :
If you want to return a warning instead of emitting it as a warning message, you could return a named list, where the warning entry in the list will be NA if no warning is generated:
mydiv = function(x, y){
warn <- NA
if (x > y)
warn <- "throw a warning"
# function calc result
return(list(value=x/y, warning=warn))
}
这篇关于R函数返回值以及警告消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!