I want to distribute an R object that is a function. For instance, say, here is my function:
f <- function(x) (x * x)
save(f, file = "f.rda")
Then,
load("f.rda")
gives me the function 'f', however, when I type
f
function(x) (x * x)
Is it possible to have this function f, but to hide what is in the source code.
I guess in some sense, I am probably asking for an equivalent to the pre-compiled "binary object file" without the source code.
Any suggestions will be greatly appreciated. I am not sure that this is necessarily possible.
CodePudding user response:
It should be possible to use a local environment / closure to do this. The following code uses a scoping assignment to expose f.
local({
g <- function (x) x * x; # "secret" algorithm!
f <<- function (x) g(x);
})
# g is not in scope here, although it is still bound in f's closure
f(4) # => 16
The result of print(f)
only covers f itself only, and not the "secret" in g:
function (x) g(x)
This naturally won't hide the original file source or textual content itself.
As I don't actually use R, I've no idea if the environment can be reflected1 to still expose g (and at some level it must be possible as a .rda file can be generated). However, this approach appears to fulfill the original requirement of not immediately exposing the algorithm.
1As @HongOoi points out, the reflected environment (and thus g) can be accessed with environment(f)$g
, which once again would expose the "secret".