58

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 函数中的作用是什么?

非常感谢您的帮助。

4

3 回答 3

39

来自?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 
于 2012-07-25T15:26:29.440 回答
26

虽然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()'s 的陷阱后,我们可以看看它的工作原理:

f2(1)

由于使用了 ,该函数不会打印其返回值invisible()。但是,它确实像往常一样传递值

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

invisible()的用例是例如防止函数返回值会产生一页又一页的输出,或者当一个函数因其副作用而被调用并且返回值仅用于提供更多信息时......

于 2016-08-11T20:15:25.923 回答
2

Tidyverse 设计指南书中的这段摘录解释了为什么返回一个不可见的值可能很有用。

如果调用一个函数主要是为了它的副作用,它应该无形地返回一个有用的输出。如果没有明显的输出,则返回第一个参数。这使得在管道中使用该函数成为可能。

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

于 2021-02-13T05:16:35.333 回答