在R 2.15中覆盖方法

6
我想知道是否有任何方法可以覆盖R包中的任何运算符方法。
以下是该包中源代码的示例:
setclass("clsTest",  representation(a="numeric", b="numeric"))
setMethod("+",  signature(x1 = "numeric", x2 = "clsTest"),
      definition=function(x1, x2) {
      Test = x2
      Test@a = Test@a+x1
      Test@b = Test@b+x1
      Test

      })

我想要覆盖现有包中的方法,使用:
setMethod("+",  signature(x1 = "numeric", x2 = "clsTest"),
          definition=function(x1, x2) {
          Test = x2
          Test@a = Test@a+(2*x1)
          Test@b = Test@b+(2*x1)
          Test

          })

我正在使用R 2.15.2,有没有办法覆盖它?


我认为,由于该方法未被封闭,您可以使用“setmethod”重新定义它。那么问题是什么? - agstudy
问题在于,我使用 [code]setMethod[/code] 重新定义后,无法再使用该方法。 - Andy
我正在考虑使用一些额外的命令来覆盖包中的方法。 - Andy
2
你需要向我们展示“could not use”的意思,即出现了什么样的失败或错误消息。 - Carl Witthoft
1个回答

1
你的代码非常接近正确,但是+的参数被称为e1e2,而不是x1x2。在使用S4时,你不能在编写方法时重命名它们。
如果你想知道它们应该被称为什么,可以使用args("+")进行检查。
正确的代码是:
setClass("clsTest",  representation(a="numeric", b="numeric")) -> clsTest
setMethod("+",  signature(e1 = "numeric", e2 = "clsTest"),
  definition=function(e1, e2) {
    Test = e2
    Test@a = Test@a+e1
    Test@b = Test@b+e1
    Test
  }
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接