R Operator Precedence
Operator Precedence
When a calculation has more than one operator, R follows rules to decide which part to calculate first, just like in math class.
For example, multiplication happens before addition:
Example
2 + 3 * 4
(2 + 3) * 4
Try it Yourself »
In 2 + 3 * 4, R calculates 3 * 4 first, so the answer is 14.
If you want the addition to happen first, use parentheses: (2 + 3) * 4 gives 20.
Tip: Use parentheses ( ) whenever you want to be sure about the order. It also makes your code easier to read.
Order of Operations
Here are the most common operators in R, from highest to lowest priority:
| Operator | Description |
|---|---|
| ( ) | Parentheses |
| ^ | Exponent |
| -x | Minus sign in front of a value |
| : | Sequence |
| %% %/% %in% | Modulus, integer division and %in% |
| * / | Multiplication and division |
| + - | Addition and subtraction |
| == != < > <= >= | Comparison |
| ! | NOT |
| & && | AND |
| | || | OR |
| <- = | Assignment |
Left to Right
Operators with the same priority, like + and -, are calculated from left to right:
Example
10 - 2 + 5
10 - (2 + 5)
Try it Yourself »
10 - 2 + 5 is calculated as (10 - 2) + 5, which is 13. With parentheses, 10 - (2 + 5) is 10 - 7, which is 3.
Watch Out for Minus
The exponent (^) is calculated before the minus sign in front of a number. So -2 ^ 2 means -(2 ^ 2):
Example
-2 ^ 2
(-2) ^ 2
Try it Yourself »
If you want to square -2, put it in parentheses: (-2) ^ 2 gives 4.