How to suppress warnings globally in an R Script

RWarnings

R Problem Overview


I have a long R script that throws some warnings, which I can ignore. I could use

suppressWarnings(expr)

for single statements. But how can I suppress warnings in R globally? Is there an option for this?

R Solutions


Solution 1 - R

You could use

options(warn=-1)

But note that turning off warning messages globally might not be a good idea.

To turn warnings back on, use

options(warn=0)

(or whatever your default is for warn, see this answer)

Solution 2 - R

You want options(warn=-1). However, note that warn=0 is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:

oldw <- getOption("warn")
options(warn = -1)

[your "silenced" code]

options(warn = oldw)

Solution 3 - R

I have replaced the printf calls with calls to warning in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings() or any of the other above mentioned methods.

suppressWarnings({ your code })

Solution 4 - R

Have a look at ?options and use warn:

options( warn = -1 )

Solution 5 - R

As discussed in other answers, you probably want to set options(warn = -1) and revert to the old behavior. The withr packages allows you to set an option value and automatically revert to the old behavior.

# install.packages("withr")

withr::with_options(.new = list(warn = -1),
                    {code})

Alternatively, the local_* functions have the same effect until the end of the function they are included in.

function() {
  withr::local_options(.new = list(warn = -1)

  { code }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichi WView Question on Stackoverflow
Solution 1 - RsiesteView Answer on Stackoverflow
Solution 2 - RFrancesco NapolitanoView Answer on Stackoverflow
Solution 3 - RBernd FischerView Answer on Stackoverflow
Solution 4 - RSimon O'HanlonView Answer on Stackoverflow
Solution 5 - RCedricView Answer on Stackoverflow