Operator overloading in R reference classes

629 Views Asked by At

I'm relatively new at OOP and need advice: What is the best way to overload the Arithmetic generic operators in reference classes in R?

For example, suppose I define

bar <- setRefClass( "foo", fields=list(a="numeric", b="numeric" ))

If I try the obvious thing:

> bar$new(a=3,b=1) + bar$new(a=1,b=3)  
Error in bar$new(a = 3, b = 1) + bar$new(a = 1, b = 3) :  
non-numeric argument to binary operator

What is the recommended way to do something like (a+a) + (b+b)?

1

There are 1 best solutions below

2
On

You can take advantage of the fact that reference classes are S4 + environments, and define an S4 method:

bar <- setRefClass("foo", fields = list(a = "numeric", b = "numeric"))
one <- bar$new(a = 1, b = 1)
two <- bar$new(a = 2, b = 2)

# Find the formals for + with getGeneric("+")
setMethod("+", c("foo", "foo"), function(e1, e2) {
  bar$new(a = e1$a + e2$a, b = e1$b + e2$b)
})
one + two

It's similarly easy to define a set of methods for a group generic:

setMethod("Ops", c("foo", "foo"), function(e1, e2) {
  bar$new(a = callGeneric(e1$a, e2$a), b = callGeneric(e1$b, e2$b))
})
one / two