invisible()函数做了什么?

R帮助将invisible()解释为“返回对象的临时不可见副本的函数”。 我很难理解什么是invisible() 。 你能解释什么是invisible() ,什么时候这个函数可以有用?

我已经看到了invisible()几乎总是用在print()方法函数中。 这里是一个例子:

 ### 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) 

我在想,如果没有invisible(x) ,我就不能像这样做:

 a = print(x) 

但事实并非如此。 所以,我想知道什么是invisible() ,它在哪里可以是有用的,最后在上面的方法print函数中它的作用是什么?

非常感谢您的帮助。

?invisible

细节:

  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. 

因此,您可以分配结果,但如果未分配,则不会打印。 它通常用来代替return 。 您的print.myPrint方法只打印,因为您明确地调用print 。 在函数结尾处对invisible(x)的调用只返回x的副本。

如果你不使用invisible ,如果没有分配, x也会被打印出来。 例如:

 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 

虽然invisible()使其内容临时不可见,并经常使用而不是return()它应该结合使用return()而不是它的替代。

虽然return()会停止函数执行并返回放入的值,但invisible()不会做这样的事情。 它只是使其内容在一段时间内不可见。

考虑以下两个例子:

 f1 <- function(x){ if( x > 0 ){ invisible("bigger than 0") }else{ return("negative number") } "something went wrong" } result <- f1(1) result ## [1] "something went wrong" f2 <- function(x){ if( x > 0 ){ return(invisible("bigger than 0")) }else{ return("negative number") } } result <- f2(1) result ## [1] "bigger than 0" 

避开invisible()的陷阱,我们可以看看它的工作:

 f2(1) 

由于使用了invisible() ,函数不会打印它的返回值。 然而它照常传递价值

 res <- f2(1) res ## [1] "bigger than 0" 

invisible()的用例是,例如,以防止函数返回值,这将产生一页一页的输出,或当一个函数被称为副作用和返回值是例如只用于提供进一步的信息…