4

I have a collection of complicated R scripts, and decided to have all my debug-related messages called via message(). I was trying to find a way to suppress all messages, and stumbled upon this SO post, which recommended I try using sink(). So I inserted the following lines of code into my script, and set my config$debug_mode <- FALSE:

if (!config$debug_mode){
  messages <- file("messages.Rout", open = "wt")
  sink(messages, type = "message")
}

The other SO post and R documentation says to simply call sink() or sink(file=NULL) to stop the previous diversion, but this is not working for me. Even after calling sink(), I don't see the R Studio console output from my message() calls. Also, sink.number() returns 0, which seems to suggest that there are no diversions in place. Why, then, am I no longer seeing output in my R Studio console?

Yu Chen
  • 6,540
  • 6
  • 51
  • 86

1 Answers1

7

When you've initially indicated that you want to sink only messages, running sink() does not turn that behavior off. Instead, use sink(type="message"), which does what you're wanting.

> config <- list()
> config$debug_mode <- FALSE
> if (!config$debug_mode){
+   messages <- file("messages.Rout", open = "wt")
+   sink(messages, type = "message")
+ }
> message("trial")
> sink(type="message")
> message("trial")
trial

This is likely what is being (obliquely) referenced in the "Warning" section of the ?sink help file, which includes this note:

Do not sink the messages stream unless you understand the source code implementing it and hence the pitfalls.

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • Appreciate that insight. However, calling `sink(type="message")` does not solve the issue. No messages are being displayed in my console. – Yu Chen Aug 29 '17 at 22:13
  • @YuChen Hmm. I wonder if that's an RStudio issue, or if there's some other detail you haven't included here. The output I just added to my post was got by running the code in the basic R for Windows GUI... – Josh O'Brien Aug 29 '17 at 22:17
  • @YuChen FWIW, I also get the same output on an (old) version of RStudio (v. 1.0.136). – Josh O'Brien Aug 29 '17 at 22:19
  • 1
    Got it working. You were right from the beginning. I had a typo: `sink(type="messages")`. – Yu Chen Aug 29 '17 at 22:21
  • @YuChen Great. Good catch. – Josh O'Brien Aug 29 '17 at 22:22
  • `message("message not printed")` followed by `message("this message is printed")` would make the example more conclusive. – Timothy M Pollington Apr 11 '22 at 07:13
  • If this is part of a function which you are replicating then the `messages` 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(messages)` as a final line. – Timothy M Pollington Apr 11 '22 at 07:54