【问题标题】:Override Method in R 2.15R 2.15 中的覆盖方法
【发布时间】:2013-03-22 08:07:53
【问题描述】:

我想知道是否有任何方法可以覆盖 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 重新定义它。那么问题出在哪里?
  • 问题是我用[code]setMethod[/code]重新定义后,就不能再使用这个方法了
  • 我正在考虑使用一些额外的命令覆盖包上的方法
  • 您需要向我们展示“无法使用”的含义,即导致什么样的失败或错误消息。

标签: r methods s4


【解决方案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
  }
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2011-09-15
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    相关资源
    最近更新 更多