222

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?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Richi W
  • 3,534
  • 4
  • 20
  • 39

5 Answers5

279

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)

Community
  • 1
  • 1
sieste
  • 8,296
  • 3
  • 33
  • 48
  • 5
    This works, but the approach of Francesco Napolitano from Sept. 22, 2015, is the safer and more globally-applicable method. – Andy Clifton Oct 23 '15 at 18:13
137

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)
Francesco Napolitano
  • 1,538
  • 1
  • 11
  • 8
  • 3
    Better than the accepted answer IMHO. If used in functions, replace the last line with `on.exit(options(warn = oldw))` to ensure resetting the options regardless of errors. – Kasper Thystrup Karstensen Oct 28 '20 at 09:16
71

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 })
Denis
  • 11,796
  • 16
  • 88
  • 150
Bernd Fischer
  • 731
  • 5
  • 3
8

Have a look at ?options and use warn:

options( warn = -1 )
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
3

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 }
}
Cedric
  • 71
  • 1
  • 5