<- 1:5
a a
[1] 1 2 3 4 5
<- 5:1
b b
[1] 5 4 3 2 1
Consider the following two vectors:
<- 1:5
a a
[1] 1 2 3 4 5
<- 5:1
b 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:
> b a
[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
.
>= b a
[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 <=
:
< b a
[1] TRUE TRUE FALSE FALSE FALSE
<= b a
[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:
== b a
[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
:
!= b a
[1] TRUE TRUE FALSE TRUE TRUE
It’s also possible to compare a vector to a single number. For example, like:
> 3 a
[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:
<- c(TRUE, TRUE, FALSE, FALSE)
a <- c(TRUE, FALSE, TRUE, FALSE) b
If we want to know where both a and b are TRUE
, we use the logical AND operator &
:
& b a
[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 |
:
| b a
[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 TRUE
s to FALSE
s and the FALSE
s to TRUE
s. 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.