invisible()函数有什么作用?

问题描述:

R帮助将invisible()解释为“返回对象的临时不可见副本的函数”。我很难理解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函数中扮演什么角色?

非常感谢您的帮助。

+13

我可以给你一个答案,但我不能显示给你。 – mdsumner 2012-07-26 05:03:47

?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()的使用情况是例如以防止函数返回值产生一页接一页的输出,或者当一个函数被称为其副作用并且返回值是例如只用于提供进一步的信息...

+1

来自其他编程语言,一旦我意识到R隐式地打印了很多东西,它就变得更有意义了。我会考虑这样的印刷副作用,而不可见()使它不这样做。 – Chris 2018-03-02 19:21:37