From http://adv-r.had.co.nz/Functions.html or R: What are operators like %in% called and how can I learn about them? I learned that it is possible to write own "binary operators" or "infix functioncs" using the %
-sign.
One example would be
'%+%' <- function(a, b) a*b
x <- 2
y <- 3
x %+% y # gives 6
But is it possible to use them in a generic way if they are from a pre-defined class (so that in some cases I don't have to use the %
-sign)? For exampple x + y
shall give 6
if they are from the class prod
.
Yes, this is possible: use
'+.<class name>' <- function()
.Examples
safety notes
The new defined functions will be called if at least one of the arguments is from the corresponding class
m + 4
gives you2 * 4 = 8
and not2 + 4 = 6
. If the classes don't match, you will get an error message (like forr + m
). So all in all, be sure that you want to establish a new function behind such basic functions like+
.