R Tutorial R Charts & Graphs R Statistics R References

R - Operators Precedence



R Operators Precedence

Operator precedence (order of operations) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given expression.

For example, multiplication has higher precedence than addition. Thus, the expression 1 + 2 × 3 is interpreted to have the value 1 + (2 × 3) = 7, and not (1 + 2) × 3 = 9. When exponent is used in the expression, it has precedence over both addition and multiplication. Thus 3 + 52 = 28 and 3 × 52 = 75.

Operator Associativity

Operator associativity is the direction in which an expression is evaluated. For example:

x = 10
y = 20

#associativity of = operator is
#Left to Right, hence x will become 20
x = y

As the associativity of = is left to right. Hence x is assigned the value of y.

Example:

The example below illustrates the operator precedence in R.

#evaluates 5 * 2 first
retval1 = 15 - 5 * 2

#above expression is equivalent to
retval2 = 15 - (5 * 2)

#forcing compiler to evaluate 15 - 5 first
retval3 = (15 - 5) * 2

cat("15 - 5 * 2 =", retval1 ,"\n")
cat("15 - (5 * 2) =", retval2 ,"\n")
cat("(15 - 5) * 2 =", retval3 ,"\n")

The output of the above code will be:

15 - 5 * 2 = 5 
15 - (5 * 2) = 5 
(15 - 5) * 2 = 20 

R Operators Precedence Table

The following table lists the precedence and associativity of R operators. Operators are listed top to bottom, in descending precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence.

Within an expression operators of equal precedence are evaluated from left to right except where indicated (Note that = is not necessarily an operator).

The binary operators ::, :::, $ and @ require names or string constants on the right hand side, and the first two also require them on the left.

PrecedenceOperatorDescription
18::  :::access variables in a namespace
17$  @component / slot extraction
16[ ]  [[ ]]indexing
15^Exponentiation operator (Right to Left)
14+a  -aUnary plus, Unary minus
13:Sequence operator
12%%  %*%  %/%  %in%  %o%  %x%Special operators
11*  /Multiplication, Division
10+  -Addition, Subtraction
9<  <=  >  >=Less than, Less than or equal, Greater than, and Greater than or equal
==  !=Equality and Inequality
8!Logical NOT
7&  &&Logical AND
6|  ||Logical OR
5~as in formulae
4->  ->>Right assignment operator, Global right assignment operator
3<-  <<-Left assignment operator, Global left assignment operator (Right to Left)
2=Left assignment operator (Right to Left)
1?help (unary and binary)

❮ R - Operators