Search code examples
roperatorsoperator-precedenceinfix-notation

In R, how can I determine the operator precedence of user defined infix operators?


Suppose I have two custom infix operators in R: %foo% and %bar%.

I have expressions that use both operators, such as:

x %foo% y %bar% z

How can I determine the operator precedence of %foo% and %bar%?

How can I change the precedence so that, for example, %bar% always executes before %foo%? In the example above this would be the same as:

x %foo% (y %bar% z)

Solution

  • I don't think this is explicitly documented, but implicit in the R language documentation is that infix operators are all of equal precedence and so are executed from left to right. This can be demonstrated as follows:

    `%foo%` <- `+`
    `%bar%` <- `*`
    1 %bar% 2 %foo% 3
    #5
    1 %foo% 2 %bar% 3
    #9
    

    The only option I can think of would be to redefine one of the existing operators to do what you wanted. However, that itself would have repercussions so you might want to limit it to within a function.

    It's also worth noting that using substitute does not change the operator precedence already set when the expression is first written:

    eval(substitute(2 + 2 * 3, list(`+` = `*`, `*` = `+`)))
    #10
    2 * 2 + 3
    #7