How to hide or disable in-function printed message

与世无争的帅哥 提交于 2019-12-17 15:55:11

问题


Suppose I have a function such as:

ff <- function(x) {
  cat(x, "\n")
  x^2}

And run it by:

y <- ff(5)
# 5 
y
# [1] 25

My question is how to disable or hide the 5 printed from cat(x, "\n") such as:

y <- ff(5)
y
# [1] 25

回答1:


You can use capture.output with invisible

> invisible(capture.output(y <- ff(2)))
> y
[1] 4

or sink

> sink("file")
> y <- ff(2)
> sink()
> y
[1] 4



回答2:


Here's a nice function for suppressing output from cat() by Hadley Wickham:

quiet <- function(x) { 
  sink(tempfile()) 
  on.exit(sink()) 
  invisible(force(x)) 
} 

Use it like this:

y <- quiet(ff(5))

Source: http://r.789695.n4.nabble.com/Suppressing-output-e-g-from-cat-td859876.html



来源:https://stackoverflow.com/questions/34208564/how-to-hide-or-disable-in-function-printed-message

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