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.
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 |
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 toHelp 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 |
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# 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
<- for assignment to keep your code consistent and clear.&& and || only evaluate the first element (useful in if conditions).& and | work with vectors.%% is very useful to find remainders, especially in loops or conditional checks.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!