Introduction
Logical operators help you check if conditions are true or false. They let you combine or change these true/false checks easily.
Logical operators help you check if conditions are true or false. They let you combine or change these true/false checks easily.
x & y # element-wise AND x | y # element-wise OR !x # NOT (negation) x && y # first element AND x || y # first element OR
& and | work on each item in vectors separately.
&& and || only check the first item of each vector.
c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE)
c(TRUE, FALSE, TRUE) | c(FALSE, FALSE, TRUE)
!c(TRUE, FALSE, TRUE)
c(TRUE, FALSE) && c(FALSE, TRUE)
This program shows how each logical operator works on vectors and single elements.
a <- c(TRUE, FALSE, TRUE) b <- c(FALSE, TRUE, TRUE) # Element-wise AND print(a & b) # Element-wise OR print(a | b) # Negation print(!a) # First element AND print(a && b) # First element OR print(a || b)
Use & and | when working with vectors to get results for each item.
Use && and || when you only want to check the first item, often in if statements.
Remember ! flips TRUE to FALSE and FALSE to TRUE.
Logical operators help combine or change TRUE/FALSE values.
& and | work on every item in vectors.
&& and || check only the first item.
& and | operate element-wise on vectors, returning a vector of TRUE/FALSE values for each element.&& and || only check the first element of the vectors and return a single TRUE/FALSE value.v in R?!, which negates each element of a logical vector.not() is not a base R function, ~ is a formula operator, and v != TRUE works but is less direct and less clear.v1 <- c(TRUE, FALSE, TRUE) v2 <- c(FALSE, FALSE, TRUE) v1 & v2 v1 && v2
v1 & v2 compares each element:v1 && v2 checks only first elements:v <- c(TRUE, FALSE, TRUE)
if (v & TRUE) {
print("Yes")
} else {
print("No")
}if statement expects a single TRUE or FALSE value, not a vector.v & TRUEv & TRUE returns a logical vector of length 3, which causes an error in if because it cannot handle multiple values.a <- c(TRUE, FALSE, TRUE, FALSE) b <- c(FALSE, TRUE, TRUE, TRUE)
a is TRUE and b is FALSE, or a is FALSE and b is TRUE. What is the resulting vector?a or b is TRUE, but not both. This is the XOR condition.(a & !b) | (!a & b) checks where a is TRUE and b is FALSE, or vice versa.Pass the test and this pattern moves unknown