-2

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?

Heiko
  • 83
  • 1
  • 8
  • Please read http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. – sgibb Sep 12 '13 at 15:20

1 Answers1

2

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))
Martin Morgan
  • 45,935
  • 7
  • 84
  • 112
  • Many thx, till now I do not watch into the object via str or dput to see that we could access to the function via a[["value"]]. – Heiko Sep 13 '13 at 07:36