How to suppress output
Asked Answered
F

2

17

I would like to suppress output in R when I run my R script from the command prompt.

I tried numerous options including --slave and --vanilla. Those options lessens the amount of text outputted.

I also tried to pipe the output to NUL but that didn't help.

Forman answered 23/3, 2010 at 16:54 Comment(1)
Maybe R is printing to stderr if > NUL doesn't help. Try appending 2>&1 as well.Nealah
E
34

Look at help(sink) to do that. On Unix I'd do

sink("/dev/null")    # now suppresses
....                 # do stuff
sink()               # to undo prior suppression, back to normal now

and the Windows equivalent (with a tip-of-the-hat to Johannes) is

sink("NUL")
....
sink()
Electroballistics answered 23/3, 2010 at 16:56 Comment(4)
Usually the Windows equivalent is NUL. However, it may well be that CreateFile, &c. won't be able to open it and that it's largely special functionality in the shell which enables its workings.Nealah
Thank you -- I edited the answer accordingly (after testing that it does indeed work that way with NUL quoted properly).Electroballistics
Hi @DirkEddelbuettel, I noted that this doesn't for dumping errors from try() sections, sink(file="NUL", type="message") complains that "NUL" isn't a file connection, in those cases one needs to use the try(stop("error msg"), silent=TRUE) for it to work as expected. Just wanted to add this to your answer in case anyone else stumbles upon this answer.Fibrovascular
So, is there a universal (platform independent) way to achieve this other than simply supplying a tempfile()?Incognizant
R
3

Since R (>= 3.6.0), there exists a platform-independent alternative to Dirk Eddelbuettel's answer. Simply type

sink(nullfile())    # suppress output
....                # your code
sink()              # end suppressing output

to suppress output on both Linux and Windows.

Ruberta answered 14/9, 2021 at 9:53 Comment(1)
If including this in a function, then can wrap inside on.exit(sink()) - otherwise unexpected errors in the function may leave you wondering why you have no output to the console.Partisan

© 2022 - 2024 — McMap. All rights reserved.