Chapter 9 Logical Operators
Welcome back to Quantitative Reasoning!
In our previous tutorial, we learned that logical vectors are a combination of
TRUE
and FALSE
elements.
In this tutorial, we’ll learn how to create new logical vectors from existing
ones with logical operators.
The most important logical operators are NOT, AND and OR.
Here are two logical vectors x
and y
.
c(TRUE, TRUE, FALSE, FALSE)
x <- c(TRUE, FALSE, TRUE, FALSE) y <-
The NOT operator negates all elements (i.e. TRUE
becomes FALSE
and vice
versa).
In R, the NOT operator is the exclamation mark.
!x
## [1] FALSE FALSE TRUE TRUE
The AND operator combines two logical vectors into a new logical vector.
The \(i\)-th element in the output is TRUE
if and only if the \(i\)-th elements
in both input vectors are TRUE
.
The AND operator in R is the ampersand.
& y x
## [1] TRUE FALSE FALSE FALSE
The OR operator also creates a new logical vector from two logical input
vectors.
Now the output element is TRUE
if at least one of the input elements is
TRUE
.
In R, the OR operator is a vertical bar.
| y x
## [1] TRUE TRUE TRUE FALSE
We can use the result of a logical operator, just like any other logical
vector, as a way to subset vectors and data frames.
Suppose we want to create a subset of the titanic
data frame that only
contains travellers on the Titanic who perished.
We achieve our goal by applying the NOT operator to the column survived
.
read.csv("~/QR/titanic/titanic.csv") titanic <-
# Data frame with travellers who perished
!titanic$survived, ] titanic[
How can we find the number of 40-year old crew members?
We must combine the conditions on age
and class
with the AND operator.
# Data frame with 40-year old crew members
$age == 40 & titanic$class == "Crew", ] titanic[titanic
Next time we discuss how we can find out how many 40-year old crew members were on board.
Let’s summarise the main points of this tutorial.
- The three most important logical operators are NOT, AND and OR.
- In R, the NOT operator is the exclamation mark.
- The AND operator is the ampersand.
- The OR operator is the vertical bar.
- Logical operators are often used to subset vectors or data frames.
In the next tutorial, we learn how to count the number of TRUE
elements in a
logical vector.
See you soon.