Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Method in R 2.15

Tags:

methods

r

s4

I would like to know if there is any way to override any operator method in R package.

Example for the source in the package:

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

      })

I would like to override the method in the existing package, with

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

          })

I am using R 2.15.2, is there any way to override it?

like image 580
Andy Avatar asked Nov 24 '22 02:11

Andy


1 Answers

Your code is very close to correct, but the arguments to + are called e1 and e2, not x1 and x2. With S4, you can't rename them when writing a method.

If you were wondering how you were supposed to know what they were called, you can use args("+") to check.

The correct code is

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
  }
)
like image 74
JDL Avatar answered Dec 15 '22 12:12

JDL