Logical expressions
Featured in 3 main posts
In programming, a logical expression (or Boolean expression) is simply a statement that can be either TRUE or FALSE. An example is the expression below:
# Is 1 equal to 2?
1==2
## [1] FALSE
As R wisely tells us, the expression is equal to the logical value FALSE, which is quite expected (1 is not, in fact, equal to 2).
By design, R can compare numeric vectors to create logical vectors, just as it does for individual values. The following expression gives a logical vector of length 2.
c(1,3)==c(2,3)
## [1] FALSE TRUE
This compares the 1st elements with each other (1==2) and the 2nd elements with each other (3==3), resulting in the logical vector [FALSE,TRUE].
Note: The double equal sign (
==) is used for comparisons (such as here), and is different from the single equal sign (=).The single equal sign is used for assignments and is equivalent to
<-in R. For example,a = 5is equivalent toa <- 5and assigns the value 5 toa(see variable assignment).
We can also store logical vectors in variables, as below:
x <- c(1,3,5)==c(2,3,4)
x
## [1] FALSE TRUE FALSE
Some operators are the following:
-
a == b:ais equal tob -
a < b:ais lower thanb -
a > b:ais higher thanb -
a <= b:ais lower than or equal tob -
a >= b:ais higher than or equal tob -
a != b:ais unequal tob -
a %in% b:ais equal to an element ofb
Logical operations
A logical expression can be made out of other subexpressions - or many subexpressions can be combined into one, depending on how you see it. For example, we may want to know if all the subexpressions are TRUE/FALSE, or if at least one of them is TRUE/FALSE.
The underlying logic is called Boolean algebra, and its most basic operations are the following:
- Logical AND (results in
TRUEif all subexpressions areTRUE):&
# Example
1==2 & 3==3
## [1] FALSE
- Logical OR (results in
TRUEif at least one subexpressions isTRUE):|
# Example
1==2 | 3==3
## [1] TRUE
- Logical NOT (converts
TRUEtoFALSEand vice versa):!
# Example
!c(1==2,3==3)
## [1] TRUE FALSE
For a comprehensive guide to R’s logical operators, check the relevant help file by running help("Logic") in the R console.
Handling logical values as numbers
Logical values (i.e. TRUE or FALSE) can also be handled as numbers in arithmetic operations (addition, multiplication, etc). The value TRUE behaves as 1 and the value FALSE behaves as 0. This is convenient for many simple calculations on logical vectors. For example, let’s look at our logical vector x:
x
## [1] FALSE TRUE FALSE
- To count all the
TRUEelements:
# The sum() function adds together all elements of a vector
sum(x)
## [1] 1
- To count all the
FALSEelements:
sum(!x)
## [1] 2
- To check if all elements are
TRUE:
# The prod() function multiplies together all elements of a vector
prod(x) # 0 if there is at least one FALSE element, otherwise 1
## [1] 0
- To check if all elements are
FALSE:
prod(!x) # 0 if there is at least one TRUE element, otherwise 1
## [1] 0