Operator Precedence and Complex Expressions
Understand evaluation order and write complex expressions safely.
What is Operator Precedence?
Operator precedence determines the order in which operations are evaluated in an expression. Just like in mathematics, multiplication is evaluated before addition. R follows a well-defined precedence table.
# Precedence in action
result1 <- 2 + 3 * 4 # * before +
result2 <- (2 + 3) * 4 # parentheses override
cat('2 + 3 * 4 =', result1, '
') # 14
cat('(2+3) * 4 =', result2, '
') # 20R Precedence Table (High to Low)
R evaluates operators in this order (highest priority first):
^— exponentiation-(unary) — negation:— sequence%%, %/%, %*%, %in%— special infix*, /— multiply, divide+, -(binary) — add, subtract<, >, <=, >=, ==, !=— comparison!— NOT&, &&— AND|, ||— OR<-, =— assignment
# Exponentiation before multiplication
cat('2 * 3 ^ 2 =', 2 * 3 ^ 2, '
') # 2 * 9 = 18
cat('(2*3)^2 =', (2 * 3) ^ 2, '
') # 6^2 = 36
# Unary minus applied after exponentiation
cat('-2 ^ 2 =', -2 ^ 2, '
') # -(2^2) = -4
cat('(-2)^2 =', (-2) ^ 2, '
') # 4All lessons in this course
- Arithmetic and Comparison Operators
- Logical Operators and Boolean Logic
- Assignment and Special Operators
- Operator Precedence and Complex Expressions