Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the print() command in R be quieted?

Tags:

r

printing

In R some functions can print information and return values, can the print be silenced?

For example:

print.and.return <- function() {
  print("foo")
  return("bar")
}

returns

> print.and.return()
[1] "foo"
[1] "bar"
> 

I can store the return like:

> z <- print.and.return()
[1] "foo"
> z
[1] "bar"
> 

Can I suppress the print of "foo"?

like image 258
ayman Avatar asked Sep 10 '10 01:09

ayman


People also ask

Is there a print function in R?

However, R does have a print() function available if you want to use it. This might be useful if you are familiar with other programming languages, such as Python, which often uses the print() function to output code.

How cat () is different from print () in R?

The simple printing method in R is to use print() . As its name indicates, this method prints its arguments on the R console. However, cat() does the same thing but is valid only for atomic types (logical, integer, real, complex, character) and names, which will be covered in the later chapters.

How do I hide the output function in R?

We can make the output should not appear. By using invisible() function we can suppress the output.

What is the difference between print and print paste in R?

The difference between: paste and paste0 is that paste function provides a separator operator, whereas paste0 does not. print ()- Print function is used for printing the output of any object in R. This recipe demonstrates an example on paste, paste0 and print function in R.


2 Answers

?capture.output
like image 168
hadley Avatar answered Oct 01 '22 09:10

hadley


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)
like image 31
mbq Avatar answered Oct 01 '22 07:10

mbq