Using logical operators

___ & ___
___ | ___
View Interactive Version

The AND operator & is a used for checking whether multiple statements are TRUE at the same time. Using a simple example, we could check whether 3 is greater than 1 and at the same time if 4 is smaller than 2:

Input
3 > 1 & 4 < 2
Output
[1] FALSE

3 is in fact greater than 1, but 4 is not smaller than 2. Since one of the statements is FALSE, the output of this joined evaluation is also FALSE.

The OR operator | checks only, whether any of the statements is TRUE.

Input
3 > 1 | 4 < 2
Output
[1] TRUE

In an OR statement, not all elements have to be TRUE. Since 3 is greater than 1, the output of this evaluation is TRUE as well.

The ! operator is used for the negation of logical values, which means it turns TRUE values to FALSE and FALSE values to TRUE. If we have a statement resulting in a logical TRUE or FALSE value, we can negate the result by applying the ! operator on it. In the following example we check whether 3 is greater than 2 and then negate the result of this comparison:

Input
!3 > 2
Output
[1] FALSE

Logical operators, just like arithmetic and relational operators, can be used on longer vectors as well. In the following example we use three different vectors a, b and c and try to evaluate multiple relations in combination.

Input
a <- c(1, 21, 3, 4)
b <- c(4, 2, 5, 3)
c <- c(3, 23, 5, 3)

a>b & b<c
Output
[1] FALSE  TRUE FALSE FALSE

First, both relational comparisons a>b and b<c are evaluated and result in two logical vectors. Therefore, we essentially compare the following two vectors:

Input
c(FALSE, TRUE, FALSE, TRUE) & c(FALSE, TRUE, FALSE, FALSE)
Output
[1] FALSE  TRUE FALSE FALSE

The & operator checks whether both values at the same position in the vectors are TRUE. If any value of the pairs is FALSE, the combination is FALSE as well.

The | operator checks whether any of the values at the same position in the vectors is TRUE.

Input
c(FALSE, TRUE, FALSE, TRUE) | c(FALSE, TRUE, FALSE, FALSE)
Output
[1] FALSE  TRUE FALSE  TRUE
Use basic operators