warnings()在函数中不起作用?如何解决这个问题? [英] warnings() does not work within a function? How can one work around this?

查看:184
本文介绍了warnings()在函数中不起作用?如何解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

op <- options(warn=0)  #although doesn't work for any value of warn
assign("last.warning", NULL, envir = baseenv())  
thisDoesntWork<- function() {
warning("HEY, this is definitely a warning!")
cat(paste("number of warnings:",length(warnings())))
}   
>thisDoesntWork()
Warning in thisDoesntWork() : HEY, this is definitely a warning!
number of warnings: 0

警告数应为1而不是0 -
似乎在函数内调用 warnings()不会返回任何东西。为什么?如果发生警告,可以如何检查功能,并打印出来?

Number of warnings should be 1 rather than 0 - it seems that warnings() returns nothing if called within a function. Why? How can one work around this to check within a function if warnings occurred, and print them out?

我不想使用 tryCatch ,因为我失去了函数返回的值(它可能仍然返回一个有效的值,即使它产生一个警告)。

I don't want to use tryCatch, because then I lose the value that the function returns (it may still return a valid value, even if it generated a warning).

推荐答案

以下是 suppressWarnings的代码

function (expr) 
{
    withCallingHandlers(expr, warning = function(w) invokeRestart("muffleWarning"))
}

我已经调整了一点,以计算警告数。

I've tweaked it a little to count the number of warnings instead.

countWarnings <- function(expr) 
{
    .number_of_warnings <- 0L
    frame_number <- sys.nframe()
    ans <- withCallingHandlers(expr, warning = function(w) 
    {
      assign(".number_of_warnings", .number_of_warnings + 1L, 
        envir = sys.frame(frame_number))
      invokeRestart("muffleWarning")
    })
    message(paste("No. of warnings thrown:", .number_of_warnings))
    ans
}

A测试:

countWarnings(log(-1))
No. of warnings thrown: 1
[1] NaN

另一个测试:

foo <- function()
{
  warning("first warning!")
  warning("second warning!")
  warning("third warning!")
  invisible()
}
countWarnings(foo())
No. of warnings thrown: 3
NULL

这篇关于warnings()在函数中不起作用?如何解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆