How can I tell if a function is being returned invisibly by a function?
Consider the following functions
f1 <- function(x) {
# do something
x
}
f2 <- function(x) {
# do something
invisible(x)
}
Suppose I call these two functions separately and store their values.
a <- f1(1)
b <- f2(2)
Is there a way to find out if a
and are not returning b
?
The motivation is that I want to create a function where if the value is returned invisibly, the function also wants to return the value invisibly.
source to share
Here withVisible
's which allows you to do this:
> f3 = function(f, x){
v=withVisible(f(x))
if(v$visible){
return(v$value)
}else{
return(invisible(v$value))
}
}
> f3(f1,1)
[1] 1
> f3(f2,1)
There is no way to do this if you have a
and b
, since identical(a,b)
- TRUE
. You can withVisible
only call an expression. If something lazy or promised doesn't happen.
source to share
A possible alternative to Spacedman's solution (own :-)) is to set the following line inside your "external" function.
if (grepl('invisible', body(inner_function) ) ) return(invisible(data)) else return(data)
Obviously this will fail if you do something creative like naming the variable "pinvisible"
source to share