Introduction to Logical Operators

In R, logical operators are used to perform logical operations. The most common logical operators are & (AND), | (OR), and ! (NOT).

# Logical AND
TRUE & TRUE
## [1] TRUE
TRUE & FALSE
## [1] FALSE
# Logical OR
TRUE | FALSE
## [1] TRUE
FALSE | FALSE
## [1] FALSE
# Logical NOT
!TRUE
## [1] FALSE
!FALSE
## [1] TRUE

Exercises

  1. Create a numeric vector named my_vector with the numbers 1 to 10.
# Your code here
my_vector <- 1:10
print(my_vector)
##  [1]  1  2  3  4  5  6  7  8  9 10
  1. Use a logical operator to select the numbers in my_vector that are greater than 5.
# Your code here
my_vector[my_vector>5]
## [1]  6  7  8  9 10
  1. Use a logical operator to select the numbers in my_vector that are less than or equal to 3.
# Your code here
my_vector[my_vector<=3]
## [1] 1 2 3
  1. Use logical operators to select the numbers in my_vector that are greater than 3 AND less than 7.
# Your code here
my_vector[my_vector>3 & my_vector<7]
## [1] 4 5 6
  1. Create a character vector named my_fruits with “apple”, “banana”, “orange”, “apple”, “grape”. Extract the elements that are equal to “apple”.
# Your code here
my_fruits <- c("apple", "banana", "orange", "apple", "grape")
my_fruits[my_fruits == "apple"]
## [1] "apple" "apple"
  1. Create a data frame with name and age columns. Extract the rows where age is greater than 25.
# Your code here
df <- data.frame(
  name = c("alif", "upoma", "rahib", "barn"),
  age = c(31, 30, 22, 4)
)
df[df$age>5, ]
##    name age
## 1  alif  31
## 2 upoma  30
## 3 rahib  22
df[df$age>25, ]
##    name age
## 1  alif  31
## 2 upoma  30
  1. Using the same data frame, extract only the name column for rows where age is greater than 25.
# Your code here
df[df$age>25, "name"]
## [1] "alif"  "upoma"

Solutions

Click here for the solutions