8

The most common place I've seen messages used in R is in the starting of a package. Suppressing one function's worth of messages is easily accomplished with suppressMessages as discussed here: Disable Messages Upon Loading Package in R. It is also possible to suppress multiple lines of message generating function calls by embedding {} inside of the supressMesssages function call. However, if you have a full script with messages happening here and there, is there anyway to disable them completely? I'm looking for something like option(warn=-1) but for messages. Please note that sink doesn't quite do what I want because it redirects all output... I would like to keep output from print but not hold onto output from message.

Community
  • 1
  • 1
russellpierce
  • 4,583
  • 2
  • 32
  • 44

1 Answers1

11

Use the type parameter in sink

# Open a file to send messages to
zz <- file("messages.Rout", open = "wt")
# Divert messages to that file
sink(zz, type = "message")
message("not gonna show up in console")
Dason
  • 60,663
  • 9
  • 131
  • 148
  • How do I make `sink()` stop again? What I need is to suppress warnings and messages when running unit tests and then turn them on again afterwards. The red output from warnings and messages make it hard to spot errors in the console. Basically, I want the equivalent of using `option(warn=-1); CODE; option(warn=0)`. An alternative idea is to embed all my unit tests in `suppressMessages()`. – CoderGuy123 Sep 26 '15 at 03:27
  • @Deleet If you type `sink()` it will end the previous sink. – russellpierce Dec 06 '16 at 20:29
  • @russellpierce calling `sink()` after executing code provided by @Dason does not bring back messages to the console for me. I've described the issue in a separate post here:https://stackoverflow.com/questions/45948882/r-output-not-appearing-after-calling-sink – Yu Chen Aug 29 '17 at 22:16
  • 3
    @russellpierce Actually, found the answer. You need to call `sink(type="message")`, and not just `sink()`. Look at the accepted answer in the SO post I linked for more details. – Yu Chen Aug 29 '17 at 22:22
  • If this is part of a function which you are replicating then the `zz` connection that has been left open will cause a `Error in file("messages.Rout", open = "wt") : all connections are in use` error on the next function call. This is solved by adding `close(zz)` as a final line. – Timothy M Pollington Apr 11 '22 at 07:52