Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress automatic output to console in R

Tags:

output

r

The function callmultmoments computes moments of the normal distribution. The function automatically prints "Sum of powers is odd. Moment is 0." if the sume of the powers is odd. Is there any way to supress that under the condition that the original function should stay untouched.

Ex:

require(symmoments)
# Compute the moment for the 4-dimensional moment c(1,1,3,4):

m.1134 <- callmultmoments(c(1,1,3,4))

EDIT:

As described here we can use

## Windows
sink("nul") 
...
sink()

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

However, I am writing a package so I want it to be platform independent. Any ideas what to do instead?

like image 214
Manuel R Avatar asked Jan 29 '18 10:01

Manuel R


People also ask

How do I not show console in R markdown?

Console Hiding If you prefer not to have the console hidden when chunks are executed, uncheck Tools -> Global Options -> R Markdown -> Hide console automatically when executing notebook chunks.

How do I suppress a message in R?

suppressPackageStartupMessages() method in R language can be used to disable messages displayed upon loading a package in R. This method is used to suppress package startup messages.

How do I save terminal output in R?

You can also save the entire R console screen within the GUI by clicking on "Save to File..." under the menu "File." This saves the commands and the output to a text file, exactly as you see them on the screen.

Can you print R console?

In R there are various methods to print the output. Most common method to print output in R program, there is a function called print() is used. Also if the program of R is written over the console line by line then the output is printed normally, no need to use any function for print that output.


1 Answers

The issue is due to the fact that the function has multiple print statements, where stop, warning, or message would have been appropriate so that people can use suppressWarnings or suppressMessages.

You can work arount it using invisible(capture.output()) around your whole assignment (not just the right side).

f1 <- function(n, ...){
    print("Random print statement")
    cat("Random cat statement\n")
    rnorm(n = n, ...)
}

f1(2)
#> [1] "Random print statement"
#> Random cat statement
#> [1] -0.1115004 -1.0830523
invisible(capture.output(x <- f1(2)))
x
#> [1]  0.0464493 -0.1453540

See also suppress messages displayed by "print" instead of "message" or "warning" in R.

like image 171
hplieninger Avatar answered Oct 09 '22 07:10

hplieninger