Operator Precedence | R Operator Precedence and Associativity - r - learn r - r programming



 r operators associativity

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 operation that will take place.
  • Precedence defines the order of execution, i.e., which operator gets the higher priority.
  • r programming operator predence

Example 1: Operator Precedence in R

>3 + 7 * 6
[1] 45
  • Here, the * operator gets higher priority than + and hence 3 + 7 * 6 is interpreted as 3 + (7 * 6).
  • This order can be changed with the use of parentheses ().
> (3 + 7) * 6
[1] 60

Operator Associativity

  • It is possible to have multiple operators of same precedence in an expression. In such case 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

>5 / 6 / 7
[1] 0.11904
  • In the above example, 5 / 6 / 7is evaluated as (5 / 6) / 7 due to left to right associativity of the / operator. However, this order too can be changed using parentheses ().
>5 / (6 / 7)
[1] 5.83

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
<, >, <=, >=, ==, != Comparisions 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

Related Searches to Operator Precedence | R Operator Precedence and Associativity