Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 792
RockScience Avatar asked Jan 20 '12 06:01

RockScience


1 Answers

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
like image 172
Martin Morgan Avatar answered Oct 04 '22 17:10

Martin Morgan