2

I am trying to overload the generic S3 add function + and multiply function *.

So far I managed to overload all the Ops (operator) functions.

foo <- structure(list(value = 1, txt = 'a'), class = 'foo')

Ops.foo <- function(e1,e2){
  structure(list(value = e1$value * e2$value,
                 txt = paste(e1$txt, e2$txt)),
            class = 'foo')
}
foo + foo # value = 1, txt = "a a"

However, I couldn't find how to do it separately for the add (+) of multiply (*) operator. I want the behavior to be different depending on if I add or multiply my new class.

I already tried the following approach:

+.foo <- function(e1,e2){
      structure(list(value = e1$value * e2$value,
                     txt = paste(e1$txt, e2$txt)),
                class = 'foo')
}

Which gave me an error saying that .foo does not exist: 'Error in +.foo <- function(e1, e2) { : object '.foo' not found'

I also tried with UseMethod() but that seems to work only for the S4 classes.

How can I overload these specific (+, *) generic S3 functions?

takje
  • 2,630
  • 28
  • 47

1 Answers1

5

Here you go

foo <- structure(list(value = 1, txt = 'a'), class = 'foo')
`+.foo` <- function(leftfoo, rightfoo) { return (paste(leftfoo$txt, rightfoo$txt)) }

and running it produces

> foo + foo
[1] "a a"
rbm
  • 3,243
  • 2
  • 17
  • 28
  • Ah the ticks. I tried it before without them and that gave me an odd error message that .foo did not exist. – takje Mar 14 '17 at 14:35