sum of S4 objects in R

筅森魡賤 提交于 2019-11-30 08:48:25

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!