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)
Run Code Online (Sandbox Code Playgroud)
我在想,如果没有invisible(x),我将无法完成如下任务:
a = print(x)
Run Code Online (Sandbox Code Playgroud)
但事实并非如此.所以,我想知道它有什么invisible()作用,它在哪里有用,最后它在上面的方法打印功能中的作用是什么?
非常感谢您的帮助.
Jos*_*ich 29
来自?invisible:
细节:
Run Code Online (Sandbox Code Playgroud)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
Run Code Online (Sandbox Code Playgroud)
pet*_*ner 12
虽然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"
Run Code Online (Sandbox Code Playgroud)
在规避了invisible()陷阱后,我们可以看看它的工作情况:
f2(1)
Run Code Online (Sandbox Code Playgroud)
由于使用,该函数不会打印其返回值invisible().然而它确实像往常一样传递价值:
res <- f2(1)
res
## [1] "bigger than 0"
Run Code Online (Sandbox Code Playgroud)
invisible()用例例如是为了防止产生页面输出的函数返回值,或者为了副作用而调用函数,并且返回值例如仅用于提供更多信息......
Tidyverse 设计指南一书中的摘录解释了为什么返回不可见值可能有用。
\n\n\n如果一个函数被调用主要是为了它的副作用,它应该\n明显地返回一个有用的输出。如果没有明显的输出,则返回第一个参数。这使得可以在管道中使用该函数。
\n
https://design.tidyverse.org/out-invisible.html
\n