[R] Method dispatch for function call operator?

Duncan Murdoch murdoch.duncan at gmail.com
Thu Jan 13 11:07:16 CET 2011


On 11-01-13 3:09 AM, Taras Zakharko wrote:
>
> Dear R gurus,
>
>   I am trying to create a nicer API interface for some R modules I have
> written. Here, I heavily rely on S3 method dispatch mechanics and
> makeActiveBinding()  function
>
>   I have discovered that I apparently can't dispatch on function call
> operator (). While .Primitive("(") exists, which leads me to believe that
> things like x(...) are internally translated to .Primitive("(")(x, ...), I
> can't seem to do something like:

The "(" function is not a function call operator.  It's essentially a 
no-op.  I believe its only purpose is to help in deparsing, so that 
things like (x + y) would deparse in the same way as entered.


>
> x<- integer()
> class(x)<- "testclass"
> "(.testclass"<- function(o, x, y) print(paste(x, y))
> x(1, 2)
>
> Similar code does work for other operators like "[".
>
> A workaround I have discovered is to make x a function from the beginning
> and then extend the functionality by via S3 methods. Unfortunately, it does
> not allow me to do something I'd really like to - use syntax like this:
>
> x(...)<- y

You can use this syntax by defining a function `x<-` <- function(...) {}
and it could be an S3 method, but it is a completely separate object from x.

Duncan Murdoch

>
> For this, I'd need to dispatch on something like
>
> "(<-.testclass"<- function(x, arglist, value)
>
> Currently, I am using the index operator for this (i.e. x[...]<- y) - it
> works nicely, but I'd prefer the () syntax, if possible.
>
>   Does anyone know a way to do this?
>



More information about the R-help mailing list