如何隐藏或禁用功能中打印的消息

Dav*_*d Z 20 printing r

假设我有一个如下功能:

ff <- function(x) {
  cat(x, "\n")
  x^2}
Run Code Online (Sandbox Code Playgroud)

并运行它:

y <- ff(5)
# 5 
y
# [1] 25
Run Code Online (Sandbox Code Playgroud)

我的问题是如何禁用或隐藏5打印的cat(x, "\n")如下:

y <- ff(5)
y
# [1] 25
Run Code Online (Sandbox Code Playgroud)

Rom*_*kyi 39

你可以用capture.outputinvisible

> invisible(capture.output(y <- ff(2)))
> y
[1] 4
Run Code Online (Sandbox Code Playgroud)

要么 sink

> sink("file")
> y <- ff(2)
> sink()
> y
[1] 4
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 9

这是一个抑制cat()Hadley Wickham的输出的好函数:

quiet <- function(x) { 
  sink(tempfile()) 
  on.exit(sink()) 
  invisible(force(x)) 
} 
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

y <- quiet(ff(5))
Run Code Online (Sandbox Code Playgroud)

资料来源:http : //r.789695.n4.nabble.com/Suppressing-output-eg-from-cat-td859876.html


Ror*_*lan 6

您还应该检查一下purrr::quietly()

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

purrr::quietly(ff)(7)$result
#> [1] 49
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020-09-10 创建