a <- 1:5
a[1] 1 2 3 4 5
b <- 5:1
b[1] 5 4 3 2 1
Consider the following two vectors:
a <- 1:5
a[1] 1 2 3 4 5
b <- 5:1
b[1] 5 4 3 2 1
To find the indices of elements where a > b, we can use a > b. This returns a logical vector which is TRUE when a is greater than b and is FALSE otherwise:
a > b[1] FALSE FALSE FALSE TRUE TRUE
Thus a>b in the 4th and 5th element only, as 4>2 in the 4th element and 5>1 in the 5th element.
For a\geq b (greater than or equal to) we use a >= b.
a >= b[1] FALSE FALSE TRUE TRUE TRUE
The condition is satisfied in the 3rd element too, as 3\geq 3.
Similarly, for “less than” we use < and for less than or equal to we use <=:
a < b[1] TRUE TRUE FALSE FALSE FALSE
a <= b[1] TRUE TRUE TRUE FALSE FALSE
For a = b, we use a == b. We need to use two equal signs, because if we did a = b, it would replace the vector a with the vector b. Thus we use == to ask if the respective elements of the two vectors are equal:
a == b[1] FALSE FALSE TRUE FALSE FALSE
Thus a=b only in the 3rd element.
For a \neq b (a not equal to b), we use a != b:
a != b[1] TRUE TRUE FALSE TRUE TRUE
It’s also possible to compare a vector to a single number. For example, like:
a > 3[1] FALSE FALSE FALSE TRUE TRUE
But what is not possible is comparing a vector with 5 elements to a vector with only 4 elements. Either the two vectors should have the same length, or at least one of them has only 1 element.
Consider the following two logical vectors:
a <- c(TRUE, TRUE, FALSE, FALSE)
b <- c(TRUE, FALSE, TRUE, FALSE)If we want to know where both a and b are TRUE, we use the logical AND operator &:
a & b[1] TRUE FALSE FALSE FALSE
a and b are only both TRUE in first element.
To see when either a or b are TRUE, we use the logical OR operator |:
a | b[1] TRUE TRUE TRUE FALSE
At least one of a or b are TRUE in all but the last element.
Suppose we wanted to return a logical vector which tells us when both a and b are FALSE. We can do that using the logical NOT operator !. First let’s see what happens when we use the NOT operator on just a:
!a[1] FALSE FALSE TRUE TRUE
Essentially it just flips the TRUEs to FALSEs and the FALSEs to TRUEs. To see when both a are b are FALSE we do:
!a & !b[1] FALSE FALSE FALSE TRUE
Thus, this only happens in the 4th element.