# R Operator Precedence and Associativity

In this article, you will learn about the precedence and associativity of operators when executing an expression in R with the help of examples.

## Operator Precedence

When multiple operators are used in a single expression, we need to know the precedence of these operators to figure out the sequence of operations that will take place.

Precedence defines the order of execution, i.e., which operator gets the higher priority.

### Example 1: Operator Precedence in R

``2 + 6 * 5``

Output

`[1] 32`

Here, the `*` operator gets higher priority than `+` and hence `2 + 6 * 5` is interpreted as `2 + (6 * 5)`. This order can be changed with the use of parentheses `()`.

``(2 + 6) * 5``

Output

`[1] 40`

## Operator Associativity

It is possible to have multiple operators of the same precedence in an expression. In such cases the order of execution is determined through associativity.

The associativity of operators is given in the table above. We can see that most of them have left to right associativity.

### Example 2: Operator Associativity in R

``3 / 4 / 5``

Output

`[1] 0.15`

In the above example, `3 / 4 / 5` is evaluated as `(3 / 4) / 5` due to left to right associativity of the `/` operator. However, this order too can be changed using parentheses `()`.

``3 / (4 / 5)``

Output

`[1] 3.75`

## Precedence and Associativity of different operators in R from highest to lowest

Operator Description Associativity
^ Exponent Right to Left
-x, +x Unary minus, Unary plus Left to Right
%% Modulus Left to Right
*, / Multiplication, Division Left to Right
+, - Addition, Subtraction Left to Right
, =, ==, != Comparisons Left to Right
! Logical NOT Left to Right
&, && Logical AND Left to Right
|, || Logical OR Left to Right
->, ->> Rightward assignment Left to Right
Leftward assignment Right to Left
= Leftward assignment Right to Left