0
0
R Programmingprogramming~5 mins

Operator precedence in R Programming

Choose your learning style9 modes available
Introduction
Operator precedence tells R which math or logic steps to do first when there are many in one line.
When you write math formulas with many operations like +, -, *, /.
When you combine conditions using AND, OR in if statements.
When you want to make sure R calculates parts of your code in the right order.
When you use parentheses to change the normal order of calculation.
When debugging why a calculation gives an unexpected result.
Syntax
R Programming
result <- expression

# Example:
result <- 2 + 3 * 4
R follows standard math rules: multiplication and division happen before addition and subtraction.
Use parentheses () to change the order and make your code clearer.
Examples
Multiplication happens first: 3 * 4 = 12, then add 2, so result is 14.
R Programming
result <- 2 + 3 * 4
print(result)
Parentheses change order: 2 + 3 = 5 first, then multiply by 4, result is 20.
R Programming
result <- (2 + 3) * 4
print(result)
Division first: 10 / 2 = 5, then add 3, result is 8.
R Programming
result <- 10 / 2 + 3
print(result)
Parentheses first: 2 + 3 = 5, then divide 10 by 5, result is 2.
R Programming
result <- 10 / (2 + 3)
print(result)
Sample Program
This program shows how R calculates with and without parentheses using operator precedence.
R Programming
a <- 5 + 2 * 3
b <- (5 + 2) * 3
c <- 10 - 4 / 2
print(a)
print(b)
print(c)
OutputSuccess
Important Notes
Remember: * and / have higher precedence than + and -.
Use parentheses to make your code easier to read and avoid mistakes.
Logical operators like && and || have lower precedence than math operators.
Summary
Operator precedence decides which part of an expression R calculates first.
Multiplication and division happen before addition and subtraction.
Parentheses can change the order and make your code clearer.