What does the function invisible() do?

Viewed 28135

R help explains invisible() as "a function that returns a temporarily invisible copy of an object". I have difficulty understanding what invisible() is used for. Would you be able to explain what invisible() does and when this function can be useful?

I've seen that invisible() is almost always used in method functions for the print(). Here is one example:

### My Method function:
print.myPrint <- function(x, ...){
  print(unlist(x[1:2]))
  invisible(x)
}

x = list(v1 = c(1:5), v2 = c(-1:-5) )
class(x) = "myPrint"
print(x)

I was thinking that without invisible(x), I wouldn't be able to do assignment like:

a = print(x)

But it's actually not the case. So, I'd like to know what invisible() does, where it can be useful, and finally what it's role is in the method print function above?

Thank you very much for your help.

3 Answers

This excerpt from the Tidyverse Design Guide book explains why it might be useful to return an invisible value.

If a function is called primarily for its side-effects, it should invisibly return a useful output. If there’s no obvious output, return the first argument. This makes it possible to use the function with in a pipeline.

https://design.tidyverse.org/out-invisible.html

Related