In R, how can I determine the operator priority for custom infix operators?

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

I have expressions that use both operators, for example:

 x %foo% y %bar% z 

How to determine the priority of the operator %foo% and %bar% ?

How to change the priority so that, for example, %bar% runs to %foo% ? In the above example, this will be the same as:

 x %foo% (y %bar% z) 
+5
source share
2 answers

I do not think this is clearly documented, but is implied in the documentation for the language in XML format , so that the infix operators have the same priority, and therefore 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 is to override one of the existing statements to do what you wanted. However, this in itself will have consequences, so you can limit it to function.

It is also worth noting that using substitute does not change the operator priority that was already set in the first expression:

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

How to determine the priority of the operator% foo% and% bar%?

You can not. R does not allow you to set the priority of user infix operators. Custom infix operators have default priority rules, which means they will be evaluated from left to right.

One of the reasons for this restriction is that it would be extremely difficult to limit the implementation and maintenance of a set of bias rules for infix operators. Imagine that you downloaded the R package, which comes with some infix user operations. Then it will be necessary to determine the relationship of the infix operators from the package with the %foo% and %bar% that you created. This will quickly become a serious burden.

As an example, suppose the packet contains the infix operator %P1IF% , and the second packet contains the infix operator %P2IF% . Each package determined that its infix operator should have the highest priority. If you were to download both packages one and two, then the following expression would be undefined:

 v1 %P1IF% v2 %P2IF% v3 (v1 %P1IF% v2) %P2IF% v3 # package 2 doesn't expect this v1 %P1IF% (v2 %P2IF% v3) # package 1 doesn't expect this 

No matter what priority may result from one of the two packages, it may be incorrect.

+2
source

All Articles