R Tutorial



R OPERATORS


Understanding Operators in R

Operators are special symbols or keywords in R that perform operations on data. They allow you to perform calculations, comparisons, logical decisions, and assignments. Mastering operators is essential to write efficient and clear R code.

1. Arithmetic Operators

These operators help you perform basic mathematical calculations.

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 7 * 6 42
/ Division 20 / 4 5
^ Exponentiation (Power) 3 ^ 2 9
%% Modulo (Remainder) 17 %% 5 2
%/% Integer Division 17 %/% 5 3

2. Relational Operators

Used to compare values and return TRUE or FALSE.

  • == : Equal to
  • != : Not equal to
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to

3. Logical Operators

Help combine multiple conditions or reverse them.

Operator Description Example Result
& Element-wise AND c(TRUE, FALSE) & c(TRUE, TRUE) TRUE, FALSE
&& Logical AND (first element only) TRUE && FALSE FALSE
| Element-wise OR c(TRUE, FALSE) | c(FALSE, FALSE) TRUE, FALSE
|| Logical OR (first element only) TRUE || FALSE TRUE
! Logical NOT !TRUE FALSE

4. Assignment Operators

Used to assign values to variables.

  • <- : Most common and recommended
  • = : Also works but can be ambiguous in function calls
  • -> : Assign value from left to variable on right

Practical Examples

# Assign values
x <- 15
y <- 4

# Arithmetic
sum <- x + y        # 19
diff <- x - y       # 11
prod <- x * y       # 60
quot <- x / y       # 3.75
power <- x ^ y      # 50625
mod <- x %% y       # 3
int_div <- x %/% y  # 3

# Relational
x == y      # FALSE
x != y      # TRUE
x > y       # TRUE
x <= y      # FALSE

# Logical
(x > 10) & (y < 10)   # TRUE
(x == 15) | (y == 10) # TRUE
!(x == y)             # TRUE

# Assignment
z = 100
200 -> w
  

Tips to Remember

  • Use <- for assignment to keep your code consistent and clear.
  • Logical operators && and || only evaluate the first element (useful in if conditions).
  • Element-wise logical operators & and | work with vectors.
  • Modulo %% is very useful to find remainders, especially in loops or conditional checks.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review