Order of operations in R

3

How does order of operations work in R? And how can I change them?

For example, when I do 1 + 2^2 in R , it knows that it is first necessary to evaluate 2^2 and then add the result with 1 .

In this case, of course, it does not make sense to want to change this order. But, what I would like to do is something like the inverse of the %>% of dplyr operator that works as follows:

exp %<% 1 + 1
# 7.389056 = exp(2)

So, it would be necessary for the 1+1 to be evaluated before %<% , is that possible?

I've tried this:

"%<%" <- function(l,r) return(l(r))
exp %<% 1 + 1
# 3.718282

But this is the same thing as:

exp(1) + 1
# 3.718282
    
asked by anonymous 03.10.2014 / 13:42

1 answer

2

I will rewrite some of my comments as an answer to the question

  

How does order of operations work in R?

@DanielFalbel, what you said has to do with the concept of "precedence" and is defined in ?Syntax , which shows the precedence of all R operators. Below I copy the R help text, showing the operators hierarchy (the first is the one with the highest precedence) :

:: :::  access variables in a namespace
$ @ component / slot extraction
[ [[    indexing
^   exponentiation (right to left)
- + unary minus and plus
:   sequence operator
%any%   special operators (including %% and %/%)
* / multiply, divide
+ - (binary) add, subtract
< > <= >= == != ordering and comparison
!   negation
& &&    and
| ||    or
~   as in formulae
-> ->>  rightwards assignment
<- <<-  assignment (right to left)
=   assignment (right to left)
?   help (unary and binary)

Note that %any% (that is, any operator defined with % % ) is one of them. That is, when defining a %<% operator, it has precedence greater than + , but less than ^ (note that in your example exp %<% 2 ^ 2 gives the result you wanted).

The problem (problem) is trying to change the precedence of your function. A trivial solution would be to use parentheses,

exp %<% (1+1)

But from what I said you wanted to avoid them.

Taking a look at the definitions of the operators, I think if it is possible this task can be quite difficult (you'll probably need to define classes that work alongside primitive operators explicitly), but I may be wrong. See ? GroupGeneric and ?S4groupGeneric for some details on how primitive operators are implemented.

    
03.10.2014 / 20:16