Question

Is there a easy way to call a function of object of a reference class by string like a do.call("...",...) for standard functions in R?

Was it helpful?

Solution

Here's a class and instance

A <- setRefClass("A",
         fields=list(x="numeric"),
         methods=list(value=function() x))
a <- A(x=10)

A funky way of invoking the value method is

> a[["value"]]
Class method definition for method value()
function () 
x
<environment: 0x123190d0>

suggesting that we could do

> do.call("[[", list(a, "value"))()
[1] 10

This has some pretty weird semantics -- the function returned by do.call seems to be independent of the instance, but actually is defined in the instance' environment

> fun = do.call("[[", list(a, "value"))
> fun
Class method definition for method value()
function () 
x
<environment: 0x1c7064c8>
> a$x=20
> fun()
[1] 20

Also, functions are instantiated in a 'lazy' way, so a[["value"]] only returns a function if it has already been called via a$value(). As discussed on ?setRefClass, I think one can force definition of the method at the time of object initialization with

A <- setRefClass("A",
         fields=list(x="numeric"),
         methods=list(
           initialize=function(...) {
               usingMethods("value")
               callSuper(...)
           },
           value=function() x))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top