Reputation: 7041
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
Upvotes: 41
Views: 34368
Reputation: 2755
You can also use the function quiet
from spsUtil library: suppress cat, print, message and warning.
Upvotes: 1
Reputation: 1042
You should also check out purrr::quietly()
.
ff <- function(x) {
cat(x, "\n")
x^2
}
purrr::quietly(ff)(7)$result
#> [1] 49
Created on 2020-09-10 by the reprex package (v0.3.0)
Upvotes: 9
Reputation: 42283
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
Upvotes: 35
Reputation: 3648
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
Upvotes: 71