2

I'm writing some text to R console using print(), cat() and message() functions. I wish to collect console outputs into a text file, so I sandwiched the code between a pair of sink() functions. Final code looks like:

sink("output_filename.txt") 
print("some text with print function")
cat("some text with cat function")
message("some text with message function")
sink()

When I run this code, print and cat work as expected while message's output writes to console and not output text file. Why does this happen and how do I work around this? I prefer not to replace message function with alternatives.

mischva11
  • 2,811
  • 3
  • 18
  • 34
Ashrith Reddy
  • 1,022
  • 1
  • 13
  • 26
  • Why don't you store it as `Rmd` and render to get same result, but with messages? – pogibas Jun 15 '19 at 05:38
  • 1
    `message()` sends to *stderr*, `print()` and `cat()` to *stdout* https://en.wikipedia.org/wiki/Standard_streams – jogo Jun 15 '19 at 06:23

1 Answers1

2

like jogo already mentioned in the commentary, message() sends to stdeer, instead of stdout. You can change this by using sink(stdout(), type = "message")

sink("output_filename.txt") 
sink(stdout(), type = "message")
print("some text with print function")
cat("some text with cat function\n")
message("some text with message function")
sink()

from documentary of sink():

Normal R output (to connection stdout) is diverted by the default type = "output". Only prompts and (most) messages continue to appear on the console. Messages sent to stderr() (including those from message, warning and stop) can be diverted by sink(type = "message") (see below).

also you might change it back after you are done, since warnings and stops are also changed to stdout this way

mischva11
  • 2,811
  • 3
  • 18
  • 34