The %in% operator Answer Key

Author

Will Gammerdinger

Published

July 1, 2025

Exercise 1

  1. Using the A and B vectors created above, evaluate each element in B to see if there is a match in A
# Return a boolean vector of elements in B that are in A
B %in% A
[1] FALSE FALSE FALSE FALSE  TRUE  TRUE
  1. Subset the B vector to only return those values that are also in A.
# Return a boolean vector of elements in B that are in A and assign it to the object intersectionBA
intersectionBA <- B %in% A

# Subset the B vector by the elements returning TRUE in intersectionBA
B[intersectionBA]
[1] 1 5

Alternatively, you can use a nested approach:

# Identify the elements in B that are in A and subset the B vector by those elements
B[B %in% A]
[1] 1 5