R uses TRUE and FALSE (or T and F) as Boolean constants.
Comparison operators are used to compare two values or expressions. They always return a Boolean value (TRUE or FALSE), which can be used directly in conditional statements, loops, or filtering.
== — checks if two values are equal.!= — checks if two values are not equal.> — checks if the left value is greater than the right.>= — checks if the left value is greater than or equal to the right.< — checks if the left value is less than the right.<= — checks if the left value is less than or equal to the right.5 == 5 # TRUE (equal)
3 != 4 # TRUE (not equal)
7 > 2 # TRUE (greater than)
2 >= 2 # TRUE (greater than or equal)
4 < 1 # FALSE (less than)Note: When comparing floating-point numbers, consider using all.equal()to avoid precision issues.
Logical operators are used to combine or modify Boolean values. They evaluate to TRUE or FALSE and are essential for building complex conditions in if statements, loops, and filtering operations.
& — element-wise logical AND (both conditions must be TRUE).| — element-wise logical OR (at least one condition must be TRUE).! — logical NOT (flips TRUE to FALSE and vice versa).&& and || — short-circuit versions of AND/OR (evaluate only the first element; used in single-condition checks).TRUE & FALSE # FALSE (both must be TRUE)
TRUE | FALSE # TRUE (at least one TRUE)
!TRUE # FALSE (negation)
# Short-circuit examples
x <- 5
y <- 10
(x > 3) && (y < 15) # TRUE
(x > 10) || (y > 8) # TRUETip: Use & and | when working with vectors, and &&/|| for single Boolean checks in control flow.
In R, logical operations are vectorized, meaning they are applied element-by-element across entire vectors without needing explicit loops. This makes operations faster, cleaner, and more expressive.
& (AND), | (OR), and ! (NOT) work on each corresponding pair of elements in two vectors.a <- c(TRUE, FALSE, TRUE)
b <- c(FALSE, FALSE, TRUE)
# Element-wise logical AND
a & b
# Output: FALSE FALSE TRUEExample of logical indexing:
nums <- c(10, 20, 30)
# Returns only elements greater than 15
nums[nums > 15]
# Output: 20 30Tip: For single TRUE/FALSE evaluations (not vectors), use && and ||instead of & and |.
Useful for understanding how logical expressions evaluate:
TRUE & TRUE # TRUE
TRUE & FALSE # FALSE
FALSE | TRUE # TRUE
FALSE | FALSE # FALSEBooleans are often used in conditional control structures:
x <- 10
if (x > 5) {
print("Greater than 5")
} else {
print("5 or less")
}== for equality, not =Ask the AI if you need help understanding or want to dive deeper in any topic