Logical operators
get_help() docs
Logical operators are symbols you can make comparisons with that tell you TRUE or FALSE. A logical statement is any piece of code that evaluates to TRUE or FALSE, i.e. code that uses a logical operator. Note that in other computing languages, these operators and statements are often called “boolean” (boo-lee-an), not logical.
Logical operators in R include the following, using placeholders X and Y to represent values/variables being compared:
| Operator | What it asks |
|---|---|
X == Y |
Is X equal to Y? |
X < Y |
Is X less than Y? |
X > Y |
Is X greater than Y? |
X <= Y |
Is X less than or equal to Y? |
X >= Y |
Is X greater than or equal to Y? |
X != Y |
Is X not equal to Y? |
!(X < Y) |
Is X not less than Y? |
!(X > Y) |
Is X not greater than Y? |
X %in% Y_ARRAY |
Is the value X present in the array Y_ARRAY? |
& |
Used to combine multiple logical statements with “and,” which means all statements must be TRUE to achieve TRUE. |
| |
Used to combine multiple logical statements with “or,” which means at least one statement must be TRUE to achieve TRUE. This symbol is known as “pipe” and is located on the backslash key above the return/enter key on your keyboard. |
Some examples below use the carnivores dataset. Learn more about this dataset with get_help("carnivores").
# Show the carnivores dataset
carnivores## # A tibble: 9 × 4
## name genus awake brainwt
## <chr> <fct> <dbl> <dbl>
## 1 Arctic fox Vulpes 11.5 0.0445
## 2 Cheetah Acinonyx 11.9 NA
## 3 Dog Canis 13.9 0.07
## 4 Gray seal Haliochoerus 17.8 0.325
## 5 Jaguar Panthera 13.6 0.157
## 6 Lion Panthera 10.5 NA
## 7 Northern fur seal Callorhinus 15.3 NA
## 8 Red fox Vulpes 14.2 0.0504
## 9 Tiger Panthera 8.2 NA
# Is 10 equal to 12?
10 == 12## [1] FALSE
# Is 14 greater than 13.5?
14 > 13.5## [1] TRUE
# Is the length of this array equal to 6?
length( c(1, 1, 2, 3, 5, 8, 13) ) == 6## [1] FALSE
# Does the following string have less than or equal to 7 characters?
nchar("im a string being evaluated") <= 7## [1] FALSE
# Is 10 greater than 5 _and_ 11 less than 10?
10 > 5 & 11 < 10## [1] FALSE
# Is 10 greater than 5 _or_ 11 less than 10?
10 > 5 | 11 < 10## [1] TRUE
# Is 55 not equal to 27?
55 != 27## [1] TRUE
# Is the word "elephant" in the following array?
"elephant" %in% c("hippopotamus", "giraffe", "zebra", "elephant")## [1] TRUE
# Is 'Panthera' in the genus column of carnivores?
"Panthera" %in% carnivores$genus## [1] TRUE