Adela
Adela

Reputation: 1797

Hiding output when saving into variable

I would like to hide printed output when saving output of my own function.

f2 <- function(x) {
  cat("x + 5 = ", x + 5)
  invisible(x + 5)
}
f2(1)       # prints
a <- f2(1)  # also prints

In other words I would like to make my function print

x + 5 = 6

when calling f2(1) but in case of calling a <- f2(1) I dont want to show any printed output. Is there any easy way how to do that?

Upvotes: 1

Views: 43

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42659

You can use a class system for this. Here's a simple S3 example:

f2 <- function(x) {
          names(x) <- paste(x, "+ 5")
          class(x) <- c(class(x), 'foo')
          x + 5
       }

print.foo <- function(x) { cat(names(x), "=", x)}

In practice:

> x <- 3
> f2(x)
3 + 5 = 8
> y <- f2(x)
> 

Note that the print.foo function does not handle vectors of length > 1 gracefully. That could be fixed, if desired.

Upvotes: 2

Related Questions