tags:

views:

82

answers:

2

In R, how can I determine whether a function call results in a warning?

That is, after calling the function I would like to know whether that instance of the call yielded a warning.

+2  A: 

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

maybe this is somehow indirect, but i don't know the more straightforward way.

kohske
Although this is inelegant, it's good because I can't find any other way to catch a warning and nevertheless return the normal result from the function. That is, if testit() returns a value, catching a warning with tryExcept means you lose the value. Unless I'm missing something?
Alex Holcombe
+3  A: 

If you want to use the try constructs, you can set the options for warn. See also ?options. Better is to 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")
> 

Using try

op <- options(warn=2)

tt <- try(x())
ifelse(is(tt,"try-error"),"There was a warning or an error","OK")
options(op)
Joris Meys