yeomii999
yeomii999

Reputation: 1

How to override binary operator for integer or numeric type?

I'm trying to override the binary operators like + or - that receive two integers or two numeric without setting class attribute.

First, I tried setMethod. But It doesn't re-define sealed operator

Second, I tried to write Ops.{class} like this link But it didn't work without setting class to S3 objects.

So, I want to know how to override + and - methods that takes integers or numerics without a class attributes.

Upvotes: 0

Views: 146

Answers (1)

user4117783
user4117783

Reputation:

If you just want to override + and - for numerics you can do that. Here's an example:

`+` <- function(x,y) x * y
 2 + 3
 [1] 6

Of course, after you've done this, you can't use + in the normal way anymore (but for reasons beyond me it seems that's what you want).

If you need some special arithmetics for numerics,it is easier to define infix operators with the %<operator>% notation. Here's an example defining the operations from max-plus algebra

`%+%` <- function(x,y) pmax(x,y) #(use pmax for vectorization)
`%*%` <- function(x,y) x + y
 2 %+% 3
 [1] 3
 2 %*% 3
 [1] 5

Another option is to define a special number class. (I'll call it tropical in the following example since max-plus algebra is a variant of tropical algebra)

setClass("tropical",slots = c(x="numeric"))

# a show method always comes in handy
setMethod("show","tropical",function(object){ 
  cat("tropical vector\n")
    print(object@x)
})

# its also nice to have an extractor
setMethod("[","tropical",function(x,i,j,...,drop) new("tropical",x=x@x[i]) )

setMethod("+",c("tropical","tropical")
  , function(e1,e2) new("tropical", x=pmax(e1@x,e2@x)) 
setMethod("*",c("tropical","tropical")
  , function(e1,e2) new("tropical", x= e1@x + e2@x))


# try it out

tr1 <- new("tropical",x=c(1,2,3))
tr2 <- new("tropical",x=c(3,2,1))


tr1 + tr2
tr1 * tr2
# this gives a warning about recycling
tr1[1:2] + tr2

Upvotes: 1

Related Questions