How to check if a function call causes a warning?

In R, how can I determine if a function call is causing a warning?

That is, after calling the function, I would like to know if this instance of the call caused a warning.

+50
r
Oct 11 '10 at 2:20
source share
4 answers

If you want to use try constructors, you can set parameters for warning. See Also ?options . Better use tryCatch() :

 x <- function(i){ if (i < 10) warning("A warning") i } tt <- tryCatch(x(5),error=function(e) e, warning=function(w) w) tt2 <- tryCatch(x(15),error=function(e) e, warning=function(w) w) tt ## <simpleWarning in x(5): A warning> tt2 ## [1] 15 if(is(tt,"warning")) print("KOOKOO") ## [1] "KOOKOO" if(is(tt2,"warning")) print("KOOKOO") 

To get both a result and a warning:

 tryCatch(x(5),warning=function(w) return(list(x(5),w))) ## [[1]] ## [1] 5 ## ## [[2]] ## <simpleWarning in x(5): A warning> 

Using try

 op <- options(warn=2) tt <- try(x()) ifelse(is(tt,"try-error"),"There was a warning or an error","OK") options(op) 
+60
Oct 11 2018-10-10T00:
source share
— -

On the R-help mailing list (see http://tolstoy.newcastle.edu.au/R/help/04/06/0217.html ), Luc Tierney wrote:

"If you want to write a function that calculates a value and collects everything, you can do it like this:

 withWarnings <- function(expr) { myWarnings <- NULL wHandler <- function(w) { myWarnings <<- c(myWarnings, list(w)) invokeRestart("muffleWarning") } val <- withCallingHandlers(expr, warning = wHandler) list(value = val, warnings = myWarnings) } 
+22
Feb 09 '11 at 16:19
source share

here is an example:

 testit <- function() warning("testit") # function that generates warning. assign("last.warning", NULL, envir = baseenv()) # clear the previous warning testit() # run it if(length(warnings())>0){ # or !is.null(warnings()) print("something happened") } 

Perhaps this is somehow indirect, but I do not know an easier way.

+6
Oct 11 2018-10-10T00:
source share

Update 2019

You can use "quietly" from the purrr package, which returns a list of output, result, warning and error. Then you can extract each item by name. For example, if you have a list with which you want to display a function and find the elements that returned a warning you could do

 library(purrr) library(lubridate) datelist <- list(a = "12/12/2002", b = "12-12-2003", c = "24-03-2005") # get all the everything quiet_list <- map(datelist, quietly(mdy)) # find the elements which produced warnings quiet_list %>% map("warnings") %>% keep(~ !is.null(.)) # or quiet_list %>% keep(~ length(.$warnings) != 0) 

For this example, this is pretty trivial, but for a long list of data frames where NA can be difficult to detect, this is quite useful.

0
Mar 27 '19 at 11:35
source share



All Articles