R中S4对象的总和

时间:2012-01-20 06:48:02

标签: r operator-overloading s4

我有一个S4类,我想定义这些对象的线性组合。

是否可以在此特定课程上发送*+个函数?

2 个答案:

答案 0 :(得分:16)

+运算符是Arith组泛型的一部分(参见?GroupGenericFunctions),因此可以使用

实现组中的所有函数
setMethod("Arith", "yyy", function(e1, e2) {
    v = callGeneric(e1@v, e2@v)
    new("yyy", v = v)
})

然后用

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)
})

一个人会

> 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

答案 1 :(得分:13)

这是一个例子:

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)

然后,

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