Сумма объектов S4 в R
У меня есть класс S4, и я бы хотел определить линейную комбинацию этих объектов.
Можно ли отправлять функции *
и +
в этом конкретном классе?
Ответы
Ответ 1
вот пример:
setClass("yyy", representation(v="numeric"))
setMethod("+", signature(e1 = "yyy", e2 = "yyy"), function (e1, e2) [email protected] + [email protected])
setMethod("+", signature(e1 = "yyy", e2 = "numeric"), function (e1, e2) [email protected] + e2)
то
> y1 <- new("yyy", v = 1)
> y2 <- new("yyy", v = 2)
>
> y1 + y2
[1] 3
> y1 + 3
[1] 4
Ответ 2
Оператор +
является частью общей группы Arith (см. ?GroupGenericFunctions
), поэтому можно реализовать все функции в группе с помощью
setMethod("Arith", "yyy", function(e1, e2) {
v = callGeneric([email protected], [email protected])
new("yyy", v = v)
})
а затем с
setClass("yyy", representation(v="numeric"))
setMethod(show, "yyy", function(object) {
cat("class:", class(object), "\n")
cat("v:", [email protected], "\n")
})
setMethod("Arith", "yyy", function(e1, e2) {
v = callGeneric([email protected], [email protected])
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