Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the function behind active binding?

Tags:

r

In R, we can use makeActiveBinding to create an active binding by supplying a function:

e <- new.env()
makeActiveBinding("var", 
  function(x) if (missing(x)) cat("get\n") else cat("set\n"), e)

Once the active binding is created, there seems no way of getting the function behind it.

I wonder if it is possible to get the function behind the active binding like the following?

> getActiveBindingFunction("var", e)
function(x) if (missing(x)) cat("get\n") else cat("set\n"), e)
like image 200
Kun Ren Avatar asked Aug 25 '16 12:08

Kun Ren


2 Answers

Since R 4.0.0 you can directly use activeBindingFunction(). It's not really documented but is straightforward enough!

e <- new.env()
makeActiveBinding("var", 
                  function(x) if (missing(x)) cat("get\n") else cat("set\n"), e)
activeBindingFunction("var", e)
#> function(x) if (missing(x)) cat("get\n") else cat("set\n")
like image 119
Moody_Mudskipper Avatar answered Oct 18 '22 22:10

Moody_Mudskipper


Answer goes out to hrbrmstr. You can coerce the environment to the list then access the function. Please see the code below:

e <- new.env()
makeActiveBinding("var", function(x) if (missing(x)) cat("get\n") else cat("set\n"), e)
as.list(e)$var

Ouput:

function(x) if (missing(x)) cat("get\n") else cat("set\n")
like image 26
Artem Avatar answered Oct 18 '22 22:10

Artem