Arithmetic Operators
& Precedence in R
Master how R evaluates mathematical expressions using operators and the order of operations that determines every result.
What Are Arithmetic Operators?
Arithmetic operators are symbols that tell R to perform a mathematical calculation on one or more values. They are the most fundamental building blocks of any R expression.
Division, Exponents, & Modulo
Why Does Precedence Matter?
When an expression contains multiple operators, R must decide which to evaluate first. The result can change dramatically depending on the order.
R's Precedence Hierarchy
Complete Precedence Table
| Priority | Operator | Description | Associativity |
|---|---|---|---|
| 1 (highest) | \(()\) | Parentheses | Inner → outer |
| 2 | \(^{\wedge}\) | Exponentiation | Right → left |
| 3 | \(-x, +x\) | Unary minus/plus | Right → left |
| 4 | \(*, /, %%, %/\%\) | Multiply, divide, modulo, integer div | Left → right |
| 5 (lowest) | \(+, -\) | Add, subtract | Left → right |
Right vs Left Associativity
When two operators have the same precedence, associativity determines the direction R reads them. Most operators go left to right, but exponentiation is different.
Parentheses Override Everything
Parentheses have the highest priority. R always evaluates the innermost parentheses first, then works outward. You can use them to force any evaluation order.
How to Evaluate Any Expression
Example 1: Step-by-Step
Evaluate: \(3 + 4 * 2^2 - 1\)
Example 2: Parentheses Change Results
Evaluate: \((8 + 2) * (9 - 4) / 2\)
Example 3: Modulo & Integer Division
Evaluate: \(20 \mathbin{\%%} 3 + 20 \mathbin{\%/\%} 3 * 2\)
The Unary Minus Surprise
In R, the unary minus (negation) has lower precedence than exponentiation. This means \(-2^2\) might not give the answer you expect.
Common Mistakes to Avoid
Quick Reference Summary
| Operator | R Syntax | Example | Result |
|---|---|---|---|
| Addition | \(+\) | \(7 + 3\) | 10 |
| Subtraction | \(-\) | \(7 - 3\) | 4 |
| Multiplication | \(*\) | \(7 * 3\) | 21 |
| Division | \(/\) | \(7 / 2\) | 3.5 |
| Exponent | \(^{\wedge}\) | \(2^5\) | 32 |
| Modulo | \(%%\) | \(17 \mathbin{\%%} 5\) | 2 |
| Integer Div | \(\%/\%\) | \(17 \mathbin{\%/\%} 5\) | 3 |
Question 1 of 5
What is the result of this R expression?
\(5 + 3 * 2\)
Question 2 of 5
What does -3^2 return in R?
Question 3 of 5
What is the result of 17 %% 5 in R?
Question 4 of 5
What does 2^3^2 evaluate to in R?
Question 5 of 5
What is the result of (4 + 6) %/% 3 + 2 * 5?