R参考类中的运算符重载

时间:2013-08-09 16:40:54

标签: r operator-overloading reference-class

我在OOP上比较新,需要建议:在R中的引用类中重载算术泛型运算符的最佳方法是什么?

例如,假设我定义

bar <- setRefClass( "foo", fields=list(a="numeric", b="numeric" ))

如果我尝试显而易见的事情:

> bar$new(a=3,b=1) + bar$new(a=1,b=3)  
Error in bar$new(a = 3, b = 1) + bar$new(a = 1, b = 3) :  
non-numeric argument to binary operator

建议采用什么方式(a + a)+(b + b)?

1 个答案:

答案 0 :(得分:2)

您可以利用参考类是S4 +环境的事实,并定义一个S4方法:

bar <- setRefClass("foo", fields = list(a = "numeric", b = "numeric"))
one <- bar$new(a = 1, b = 1)
two <- bar$new(a = 2, b = 2)

# Find the formals for + with getGeneric("+")
setMethod("+", c("foo", "foo"), function(e1, e2) {
  bar$new(a = e1$a + e2$a, b = e1$b + e2$b)
})
one + two

为组通用定义一组方法同样容易:

setMethod("Ops", c("foo", "foo"), function(e1, e2) {
  bar$new(a = callGeneric(e1$a, e2$a), b = callGeneric(e1$b, e2$b))
})
one / two