1

Is it possible to define (+) function by R, s.t. able to work between its two arguments?

In other words, I'd like to delete % from the following infix function (but I can not and I don't know how this problem can be solved):

`%(+)%` <- function(x,y)  { x+(2*y) }
2 %(+)% 3
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453

2 Answers2

3

User-defined infix operators must be surrounded by percent signs in R. So the answer to your question is, "you can't". Sorry.

From the R language definition:

R allows user-defined infix operators. These have the form of a string of characters delimited by the ‘%’ character. The string can contain any printable character except ‘%’. The escape sequences for strings do not apply here.

The only alternatives I can think of, both rather desperate:

  • if x and y are defined as members of an S4 class then you can overload dispatch for the + symbol
  • you could hack the R parser (not recommended!), as in this example, where someone forked a read-only Github mirror of R to modify the parser (described here).
Community
  • 1
  • 1
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
1

I agree with Ben Bolker that you cannot define (+) without the %. However, if you are looking to create a function as per above why not use the following:

`&`<- function(x, y) { x+(2*y) }
2&3
#Use rm to remove the defined function
rm(`&`) 
TsTeaTime
  • 881
  • 1
  • 13
  • 34
  • Actually you cannot define + as per the requirement because it would lead to an infinite recursion error since you are defining something that he is using in the actual function. – TsTeaTime Mar 28 '16 at 02:08