Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

r - What does the function invisible() do?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From ?invisible:

Details:

 This function can be useful when it is desired to have functions
 return values which can be assigned, but which do not print when
 they are not assigned.

So you can assign the result, but it will not be printed if not assigned. It's often used in place of return. Your print.myPrint method only prints because you explicitly call print. The call to invisible(x) at the end of your function simply returns a copy of x.

If you didn't use invisible, x would also be printed if not assigned. For example:

R> print.myPrint <- function(x, ...){
+   print(unlist(x[1:2]))
+   return(x)
+ }
R> print(x)
v11 v12 v13 v14 v15 v21 v22 v23 v24 v25 
  1   2   3   4   5  -1  -2  -3  -4  -5 
v11 v12 v13 v14 v15 v21 v22 v23 v24 v25 
  1   2   3   4   5  -1  -2  -3  -4  -5 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...