1.13 Logical operators
The basic logical values in R are TRUE
(or just T
) and FALSE
(or just F
). These come up very often in R when you are checking an object, for example using is.na(x)
, or comparing an object to a value or another object, as in x > 5
or x > y
.
Some commonly used logical operators:
>
(greater than)>=
(greater than or equal to)<
(less than)<=
(less than or equal to)==
(equal to)!=
(not equal to)
Many of these are exactly what you would expect (like >
) but remember to use TWO equal signs rather than one when assessing equality (==
not =
). If you use just one equal sign, R thinks you are trying to assign a value to an object.
## [1] TRUE
You can combine logical conditions using &
(and), |
(or), and !
(not).
## [1] TRUE
## [1] FALSE
## [1] TRUE
## [1] TRUE
You can apply logical operators elementwise to vectors or matrices.
## [1] TRUE TRUE FALSE
Some additional useful operators are the following.
any()
(TRUE if any element meets the condition)all()
(TRUE if all elements meet the condition)%in%
(TRUE if any element is in the following vector)
## [1] TRUE
## [1] FALSE
# Check if EACH element of x is equal to ANY of
# the elements of the object on the right
x %in% c(0, 1, 2)
## [1] FALSE TRUE TRUE
x %in% c(0, 1, 2)
returned FALSE, TRUE, TRUE because the first element of x
(-1) is not in the vector c(0, 1, 2)
, but the other two elements of x
(0 and 1) are.
R also has the logical operators &&
and ||
. According to the R help (?'&&'
), “& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.” If you do not understand this paragraph, then do not use &&
or ||
. For the purpose of this text, you will not need them.
You can convert logical values to 0s and 1s using as.numeric()
or by multiplying by 1.
## [1] TRUE TRUE FALSE
## [1] 1 1 0
## [1] 1 1 0
A common use of logical operators is to subset a vector or matrix based on some condition.
## [1] -5 -4 -3 -2 -1 0 1 2 3 4 5
## [1] 0 1 2 3 4 5
## [1] -5 -4 -3 3 4 5
Be careful of missing values
When using a logical operator to subset an object in base R, missing values can lead to unexpected results. Consider the vector below that has some missing values and what happens when we attempt to subset it to include only the values greater than 5.
## [1] NA 8
The missing value is treated as if it meets the logical condition, which is often not what is intended. Instead, explicitly exclude missing values from the logical subset statement.
## [1] 8
So if you just want the non-missing values that meet the condition, make sure to explicitly exclude the missing values.