Can the print() command in R be quieted?

拟墨画扇 提交于 2019-12-21 04:12:54

问题


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"?


回答1:


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)



回答2:


?capture.output



回答3:


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"
> 



回答4:


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())



回答5:


I know that I might be resurrecting this post but someone else might find it as I did. I was interested in the same behaviour in one of my functions and I just came across "invisibility":

It has the same use of return() but it just don't print the value returned:

invisible(variable)

Thus, for the example given by @ayman:

print.and.return2 <- function() {
  message("foo")
  invisible("bar")
}


来源:https://stackoverflow.com/questions/3681719/can-the-print-command-in-r-be-quieted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!