Arithmetic operators in R perform basic mathematical operations. They work on numeric data and return a numeric result. These include addition, subtraction, multiplication, division, modulus (remainder), and exponentiation.
+ — addition- — subtraction* — multiplication/ — division (always returns a decimal for non-divisible numbers)%% — modulus (remainder after division)^ — exponentiation (power)a <- 10
b <- 3
a + b # 13
a - b # 7
a * b # 30
a / b # 3.333
a %% b # 1 (modulus)
a ^ b # 1000 (exponent)Relational (comparison) operators compare two values and return a logical value (TRUE or FALSE). They are used in conditions for filtering, branching, and loops.
== — equal to!= — not equal to> — greater than< — less than>= — greater than or equal to<= — less than or equal toa <- 5
b <- 7
a == b # FALSE
a != b # TRUE
a > b # FALSE
a < b # TRUE
a >= 5 # TRUE
b <= 10 # TRUELogical operators combine or modify logical values (TRUE / FALSE). They are often used in conditional statements or filtering operations.
& — element-wise AND (checks each element in vectors)| — element-wise OR! — logical NOT (negates the value)&& — short-circuit AND (evaluates only the first element, used for single conditions)|| — short-circuit OR (evaluates only the first element)x <- TRUE
y <- FALSE
x & y # FALSE (element-wise AND)
x | y # TRUE (element-wise OR)
!x # FALSE (NOT x)Use && and || for single-condition evaluation in control flow.
Assignment operators store values in variables. In R, the most common is <-, which is preferred in most style guides. The equals sign (=) is also valid but more often used for function arguments. The rightward assignment (->) is rare and mainly used for specific readability purposes.
<- — assign value to a variable (preferred)= — assign value (common in other languages, valid in R)-> — assign value from left to rightx <- 5 # preferred
y = 10 # also works
15 -> z # rare but validUse <- for consistency across R codebases and to avoid confusion with equality checks.
1:5 # creates a sequence from 1 to 5
"b" %in% c("a", "b", "c") # TRUE
A <- matrix(1:4, nrow=2)
B <- matrix(1:4, nrow=2)
A %*% B # matrix multiplication= versus <- for assignmentsAsk the AI if you need help understanding or want to dive deeper in any topic