29

I would like to write an R function that returns silently, like what I get from the barplot function for example.

I mean that I can store an output in a variable if I do output = myfunction(), but this output does not get printed if I just use myfunction().

Math
  • 2,399
  • 2
  • 20
  • 22

2 Answers2

30
myFunc <- function(x){
  invisible(x*2)
}

> myFunc(4)
> y <-myFunc(4)
> y
[1] 8
> 
jdharrison
  • 30,085
  • 4
  • 77
  • 89
  • Mostly likely a duplicate – jdharrison Jun 09 '14 at 14:36
  • 3
    I would say it is usefull to keep this question for the keywork `silent` (instead of invisible). If you do not agree, I can delete it. – Math Jun 09 '14 at 14:53
  • It shouldn't be deleted the question is can a duplicate be found that has already addressed the question. – jdharrison Jun 09 '14 at 14:55
  • 7
    I found it by searching 'silent', not 'invisible' – David F May 05 '18 at 16:32
  • There's a problem with `invisible` though. If there is any code after the call to `invisible`, the function keeps going (it doesn't exit, as it would for `return`). `foo <- function(x=2) { invisible(x); print(1) }` called as `x <- foo()` should return 2, but instead keeps assigning 1 to x. This means that when `invisible` is not the end of the function (say you wanted to use a silent exit under some condition), you'll get unexpected results. – Dannid Oct 14 '22 at 23:49
  • Playing around, it looks like you can wrap `invisible` in `return`, like so: `foo <- function(x=2) { return(invisible(x)); print(1) }` and this works just like I would expect. – Dannid Oct 15 '22 at 00:01
0

invisible() can be called at the end of the function to suppress any return value. Only downside is function will return NULL.

xf <- function() {
3 + 4
invisible()
}
close2zero
  • 85
  • 8