8

I am looking to redirect stderr and stdout messages to an output file. Here's what I tried:

sink("outputFile" ,type = c("output", "message"))
print("using print")
cat("using cat\n")
message("using message")
warning("using warning")

When I run this code, I still see "using message" and "using warning" in my R console, and it's not being redirected.

Is there a way to redirect both stdout and stderr to a file? I used this code to redirect my stderr to stdout, but that's not exactly what I'm looking for.

sink(stdout(), type = "message") # sink messages to stdout
Bschrein
  • 83
  • 1
  • 4

2 Answers2

16

You need to do it in two steps, using something like this:

zz <- file("test.txt", open = "wt")
sink(zz ,type = "output")
sink(zz, type = "message")
print("using print")
cat("using cat\n")
message("using message")
warning("using warning")
#and to close connections
sink()
sink()

enter image description here

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
  • Thanks a bunch. Exactly what I was looking for. – Bschrein Jan 09 '18 at 17:47
  • 1
    this is not enough; the code for closing everything correctly is missing - and this part is not trivial... – Tomas Jun 26 '19 at 13:08
  • I was still having trouble getting the warning to appear with this answer - I had to add an argument `warning("using warning", immediate. = T)` or change the global options with `options(warn=1)` in order to have the warning delivered immediately. – lauren.marietta Apr 22 '20 at 17:45
0

I think that there is something missing to the previous answer: Both final "sink()" should be specifying the type of sink you close, and then close the file. In that way you fully close the connection.

zz <- file("test.txt", open = "wt")
sink(zz ,type = "output")
sink(zz, type = "message")
print("using print")
cat("using cat\n")
message("using message")
warning("using warning")
#and to close connections
sink(type="message")
sink(type="output")
close(zz)
TomTom
  • 11
  • 2