Are binary operators / infix functions in R generi

2019-09-17 15:56发布

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.

1条回答
你好瞎i
2楼-- · 2019-09-17 17:00

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 +.

查看更多
登录 后发表回答