How can I check whether a function call results in a warning?

trycatch r
r capture warning messages
r trycatch continue
r if error return na
r try skip error
r try-catch suppress error message
if(error) in r
error in value((3l))(cond attempt to apply non function)

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.

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

tt <- tryCatch(x(5),error=function(e) e, warning=function(w) w)

tt2 <- tryCatch(x(15),error=function(e) e, warning=function(w) w)

## <simpleWarning in x(5): A warning>

## [1] 15

if(is(tt,"warning")) print("KOOKOO")
## [1] "KOOKOO"

if(is(tt2,"warning")) print("KOOKOO")

To get both the result and the 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")

Exceptions and debugging � Advanced R., You can tell them apart because errors always start with “Error” and warnings with Debugging tools introduces you to the R functions and RStudio features that error inspector and traceback() which list the sequence of calls that lead to the� 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.

On the R-help mailing list (see, Luke Tierney wrote:

"If you want to write a function that computes a value and collects all warning you could do it like this:

withWarnings <- function(expr) {
    myWarnings <- NULL
    wHandler <- function(w) {
        myWarnings <<- c(myWarnings, list(w))
    val <- withCallingHandlers(expr, warning = wHandler)
    list(value = val, warnings = myWarnings)

8 Conditions, You can tell them apart because errors always start with “Error”, warnings with Unlike errors, you can have multiple warnings from a single function call: Compare the results of tryCatch() and withCallingHandlers() in the example below. You can do this by piping check_function()into check_result(), check_output(), or check_error(), depending on whether you want to check the result of the function call, the output the function call generates, or the error the call generates.

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.

Checking Arguments in R Functions, This results in the function producing an error the user doesn't note, and the finishArgCheck will call stop if there are any errors and warning if� The result of the (evaluated) function call. Warning. This should not be used to attempt to evade restrictions on the use of .Internal and other non-API calls. References. Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. See Also. call which creates an unevaluated call. Examples

2019 update

You can you use 'quietly' from the purrr package, which returns a list of output, result, warning and error. You can then extract each element by name. For instance, if you had a list, which you want to map a function over, and find the elements which returned a warning you could do


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 it's quite trivial, but for a long list of dataframes where the NAs might be hard to spot, this is quite useful.

withCallingHandlers + tryCatch, The tryCatchLog package provides an advanced tryCatch function for the Easy logging of errors, warnings and messages into a file or console Note that the output does not show the print result since the execution stops in case of an error. If you do not catch an error R stops and you can get the complete function call� The only requirement in any function call is that the expression before the parentheses must evaluate to a function address. This means that a function can be called through any function-pointer expression. Example. This example illustrates function calls called from a switch statement:

Using R — Basic error Handing with tryCatch(), (The documentation for these functions will lead to all the other error-related functions for any RTFM result = tryCatch({ expr }, warning = function(w) control is transferred to the 'tryCatch' call that established the handler [. Here Mudassar Ahmed Khan has explained with an example, how to call JavaScript function when an HTML RadioButton is checked (selected) or unchecked (unselected). For illustration purposes, when the RadioButton is clicked based on whether it is checked (selected) or unchecked (unselected), a JavaScript function will be called within which the HTML DIV with TextBox will be shown or hidden.

Code Diagnostics – RStudio Support, Check arguments to R function calls. Try to detect whether a particular call to a function will succeed. The diagnostics engine will report if it� Notice how much cleaner that warning message looks now! Using the warning instead of the error, the function is able to evaluate where the values are appropriate while still informing the user of any changes made to the inputs. Whether or not this is a good idea is up for debate, and in most cases, I would argue that it is not a good idea

options function, This facilitates retrieving an option and checking whether it is set and setting it Invoking options() with no arguments returns a list with the current values of the options. If true, a warning is produced whenever a vector (atomic or list ) is extended, If the option is a function, a call to that function, with no arguments,� The answer is in your question; your function name is 'warning' so start with that: ' ();' This is the method to call a function. Good luck. Posting to the forum is only allowed for members with active accounts. Please sign in or sign up to post.

  • Check out if ?try does what you want.
  • Closely related to that provides some excellent answers with error catching as well.
  • thanks for your edit showing how to get both the result and the warning; however, the function is called twice when there's a warning. Can it be done with only one call (in case the function is slow, for example)?
  • @Aaron : then I'd go for the handlers as shown below by you. That's the cleanest way, and those are made to do that. It just requires a bit more puzzling.
  • Thanks. It is definitely puzzling. Though it does what I need, there's a lot in that code I don't yet understand.
  • Yup, that way it updates the myWarnings outside the function; otherwise it makes a new myWarnings inside the function and the outside one doesn't get updated.
  • 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 : you could do pretty easily using a tryCatch formula. You can do something with the warning in the argument, eg: warning=function(w) { something ... return(normal result)}
  • @Joris: I couldn't get tryCatch to return the normal result. Am I missing something? I did find a way using withCallingHandlers, from the R mailing list (included as a separate answer).
  • @AlexHolcombe You could also set options(warn=1) in which case the warnings are printed to stdout rather than stderr.