Is it possible to define an operator without %%?

User-defined operators are allowed in R, but it seems that only the same%% is accepted as operators. Is there a way around this limitation to define operators, for example >> or something that does not look like%%?

The operator must be a real operator, so we can use it as 1 >> 2 and should not use it as ">>"(1,2) .

+8
r operator-keyword
source share
2 answers

Not. R allows only

  • override existing operators (e.g. + or, indeed, <- ),
  • define new infix operators, surrounding them with %…% .

These are the rules we must play. However, inside these rules everything is fair and games. For example, we can override + for character strings to perform concatenation without destroying its normal value (addition):

 > `+` function (e1, e2) .Primitive("+") 

This is the old definition that we want to keep for numbers:

 > `+.default` = .Primitive('+') > `+.character` = paste0 > `+` = function (e1, e2) UseMethod('+') > 1 + 2 [1] 3 > 'hello' + 'world' [1] "helloworld" 

This uses the S3 class system in R to do + generic as its first argument.

The list of operators that can be overridden is quite eclectic. At the first count, it contains the following operators:

+ , - , * , / , ^ , ** , & , | , : , :: , ::: , $ , $<- , = , <- , <<- , == , < , <= , > , >= != , ~ , && , || ! , ? , ?? , @ , @<-

(taken from the source code of the modules .)

Alternatively, you can override -> by overriding <- . It seems like this rarely makes sense - but at least one good example of this exists to define less verbose lambdas:

 > sapply(1 : 4, x -> 2 * x) [1] 2 4 6 8 

Implementation as an entity

+12
source share

You can do such things, but you might want to assign these objects to a new safe environment.

 > "^" <- function(x, y) `-`(x, y) ## subtract y from x > 5 ^ 3 # [1] 2 > "?" <- function(x, y) sum(x, y) ## add x and y > 5 ? 5 # [1] 10 
+4
source share

All Articles