2

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.

Community
  • 1
  • 1
Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • 4
    This is how `ggplot2` works - `ggplot(data,aes(x=a,y=b)) + geom_point()` uses an overridden `+` method. – Spacedman Jan 26 '17 at 17:29
  • 1
    The quick answer is "yes". When you search on `?Ops` you should see the option of looking at 2 help pages that confirm this for either S3 or S4 styles of function definition. – IRTFM Jan 26 '17 at 18:00
  • [Related](http://stackoverflow.com/questions/4730551/making-a-string-concatenation-operator-in-r) – Hong Ooi Jan 27 '17 at 13:36

1 Answers1

2

Yes, this is possible: use '+.<class name>' <- function().

Examples

'+.product' <- function(a, b) a * b
'+.expo' <- function(a, b) a ^ b

m <- 2; class(m) <- "product"
n <- 3; class(n) <- "product"

r <- 2; class(r) <- "expo"
s <- 3; class(s) <- "expo"

m + n # gives 6
r + s # gives 8

safety notes

The new defined functions will be called if at least one of the arguments is from the corresponding class m + 4 gives you 2 * 4 = 8 and not 2 + 4 = 6. If the classes don't match, you will get an error message (like for r + m). So all in all, be sure that you want to establish a new function behind such basic functions like +.

Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • 3
    I think it would be fairly unwise to use "prod`' as a class name because it is also an R function name. You might also consider including references to appropriate help pages to improve the answer. – IRTFM Jan 26 '17 at 17:57
  • Thank you @42- for the hints. I changed it to `product`. If I find useful help pages, I will include them. – Qaswed Apr 20 '17 at 12:37