R function return value as well warning message

时光怂恿深爱的人放手 提交于 2019-12-23 22:40:55

问题


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)
})
}

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.


回答1:


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)
}

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))
}


来源:https://stackoverflow.com/questions/35858209/r-function-return-value-as-well-warning-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!