如何覆盖 R 中的警告

oli*_*roy 10 error-handling r rlang

我有一个函数可以生成不需要的警告,但保留该值。

f <- function(a) { 
  
  if (a > 1) { 
    warning("an uninformative warning")
  }
  a
}

g1 <- function(b) {
  
  withCallingHandlers(
    x <-f(b),
    warning = function(w) {
      warning("A more informative warning")
    })
  
  x
}
g1(2)
#> Warning in (function (w) : A more informative warning
#> Warning in f(b): an uninformative warning
#> [1] 2
Run Code Online (Sandbox Code Playgroud)

创建于 2023 年 12 月 12 日,使用reprex v2.0.2

不幸的是,这会出现 2 个警告。

tryCatch()不保留 x 。和withCallingHandlers(),两个警告都会被抛出。

All*_*ron 14

您可以让warning处理程序发出自己的警告,然后调用muffleWarning重新启动:

f <- function(a) { 
  
  if (a > 1) { 
    warning("an uninformative warning")
  }
  a
}

g1 <- function(b) {
  
  withCallingHandlers(
    x <- f(b),
    warning = function(w) {
      warning('A more informative warning', call. = FALSE)
      tryInvokeRestart("muffleWarning")
    })
  x
}
Run Code Online (Sandbox Code Playgroud)

测试:

g1(2)
#> [1] 2
#> Warning message:
#> A more informative warning
Run Code Online (Sandbox Code Playgroud)