0Pricing
R Academy · Lesson

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, '
')   # 20

R Precedence Table (High to Low)

R evaluates operators in this order (highest priority first):

  1. ^ — exponentiation
  2. - (unary) — negation
  3. : — sequence
  4. %%, %/%, %*%, %in% — special infix
  5. *, / — multiply, divide
  6. +, - (binary) — add, subtract
  7. <, >, <=, >=, ==, != — comparison
  8. ! — NOT
  9. &, && — AND
  10. |, || — OR
  11. <-, = — 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, '
')  # 4

All lessons in this course

  1. Arithmetic and Comparison Operators
  2. Logical Operators and Boolean Logic
  3. Assignment and Special Operators
  4. Operator Precedence and Complex Expressions
← Back to R Academy