sum of S4 objects in R

前端 未结 2 779
無奈伤痛
無奈伤痛 2020-12-31 10:53

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

相关标签:
2条回答
  • 2020-12-31 11:14

    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
    
    0 讨论(0)
  • 2020-12-31 11:19

    The + operator is part of the Arith group generic (see ?GroupGenericFunctions) so one can implement all functions in the group with

    setMethod("Arith", "yyy", function(e1, e2) {
        v = callGeneric(e1@v, e2@v)
        new("yyy", v = v)
    })
    

    and then with

    setClass("yyy", representation(v="numeric"))
    setMethod(show, "yyy", function(object) {
        cat("class:", class(object), "\n")
        cat("v:", object@v, "\n")
    })
    setMethod("Arith", "yyy", function(e1, e2) {
        v = callGeneric(e1@v, e2@v)
        new("yyy", v = v)
    })
    

    One would have

    > y1 = new("yyy", v=1)
    > y2 = new("yyy", v=2)
    > y1 + y2
    class: yyy 
    v: 3 
    > y1 / y2
    class: yyy 
    v: 0.5 
    ## ...and so on
    
    0 讨论(0)
提交回复
热议问题