Search code examples
roperator-overloadingr-s4

sum of S4 objects in R


I have a S4 class and I would like to define the linear combination of these objects.

Is it possible to dispatch * and + functions on this specific class?


Solution

  • here is an example:

    setClass("yyy", representation(v="numeric"))
    
    setMethod("+", signature(e1 = "yyy", e2 = "yyy"), function (e1, e2) e1@v + e2@v)
    setMethod("+", signature(e1 = "yyy", e2 = "numeric"), function (e1, e2) e1@v + e2)
    

    then,

    > y1 <- new("yyy", v = 1)
    > y2 <- new("yyy", v = 2)
    > 
    > y1 + y2
    [1] 3
    > y1 + 3
    [1] 4