Can the print() command in R be quieted?
I agree with hadley and mbq's suggestion of capture.output
as the most general solution. For the special case of functions that you write (i.e., ones where you control the content), use message
rather than print
. That way you can suppress the output with suppressMessages
.
print.and.return2 <- function() {
message("foo")
return("bar")
}
# Compare:
print.and.return2()
suppressMessages(print.and.return2())
If you absolutely need the side effect of printing in your own functions, why not make it an option?
print.and.return <- function(..., verbose=TRUE) {
if (verbose)
print("foo")
return("bar")
}
> print.and.return()
[1] "foo"
[1] "bar"
> print.and.return(verbose=FALSE)
[1] "bar"
>
?capture.output
You may use hidden functional nature of R, for instance by defining function
deprintize<-function(f){
return(function(...) {capture.output(w<-f(...));return(w);});
}
that will convert 'printing' functions to 'silent' ones:
noisyf<-function(x){
print("BOO!");
sin(x);
}
noisyf(7)
deprintize(noisyf)(7)
deprintize(noisyf)->silentf;silentf(7)