Logical Operators and Boolean Logic
Understand &, |, !, xor(), any(), and all() for Boolean operations.
Introduction to Boolean Logic
Boolean logic is the foundation of decision-making in programming. In R, logical values are TRUE and FALSE. Logical operators combine these values to form complex conditions.
# Boolean values in R
is_raining <- TRUE
is_cold <- FALSE
cat('Is raining:', is_raining, '
')
cat('Is cold:', is_cold, '
')
cat('Class:', class(is_raining), '
')Element-wise AND with &
The & operator performs element-wise AND on vectors. It returns TRUE only when both corresponding elements are TRUE. It processes every element in a vector.
ages <- c(15, 22, 17, 30, 19)
has_id <- c(FALSE, TRUE, FALSE, TRUE, TRUE)
# Can buy alcohol? (must be 18+ AND have ID)
can_buy <- (ages >= 18) & has_id
cat('Ages >= 18:', ages >= 18, '
')
cat('Has ID:', has_id, '
')
cat('Can buy:', can_buy, '
')All lessons in this course
- Arithmetic and Comparison Operators
- Logical Operators and Boolean Logic
- Assignment and Special Operators
- Operator Precedence and Complex Expressions