user31264
user31264

Reputation: 6727

How to temporarily suppress warnings in R

Currently I write:

warn = getOption("warn")
options(warn=-1)
foo()
options(warn=warn)

Is there a better solution?

Upvotes: 32

Views: 27495

Answers (3)

kodi1911
kodi1911

Reputation: 722

If you want to skip more than one warning, you can wrap your code into withCallingHandlers() function.

For example:

withCallingHandlers({
    print("prt1")
    warning("warn1")
    message("msg1")
    print("prt2")
    warning("warn2")
    message("msg2")
},
warning = function() { return(NULL) })

There is also a possibility to omit messages(), by adding message = function() { return(NULL) }) as an extra argument in the withCallingHandlers() function. Moreover, there is an argument to pass your error function handler, but, when an error appears, it goes into the error handler function and won't execute remaining code in brackets.

Upvotes: 1

Vincent Bonhomme
Vincent Bonhomme

Reputation: 7443

You wrap an expression in suppressWarnings() (yet here foo() returns an error, not a warning).

Upvotes: 5

Thomas
Thomas

Reputation: 44525

Use suppressWarnings():

suppressWarnings(foo())

Upvotes: 50

Related Questions