R Identify Elements in One Vector that are not Contained in Another (2 Examples)

This article illustrates how to find out which values are contained in one vector, but not in a second vector in the R programming language.

Introduction of Example Data

my_first_vector <- LETTERS[1:5]                                  # Example vectors (characters)
my_second_vector <- LETTERS[4:10]

Example 1: Apply %in%-Operator to Find Values Contained Only in the First Vector

my_first_vector[my_first_vector %in% my_second_vector == FALSE]  # Using %in%
# "A" "B" "C"

Example 2: Apply setdiff() Function to Find Values Contained Only in the First Vector

setdiff(my_first_vector, my_second_vector)                       # Using setdiff
# "A" "B" "C"

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top