Find Values Contained in First Vector but not Another in R (2 Examples)


In this R programming post you’ll learn how to find out which values are contained in one vector, but not in a second vector.

The article will consist of two examples for the identification of unique values. More precisely, the tutorial consists of these content blocks:

It’s time to dive into the examples.


Example Data

The following data is used as basement for this R programming language tutorial:

vec1 <- 1:10                  # Create & print example vectors
# 1  2  3  4  5  6  7  8  9 10
vec2 <- 6:15
# 6  7  8  9 10 11 12 13 14 15

The previous output of the RStudio console shows that our exemplifying data consists of two numeric vectors (or arrays) with a different range of values.


Example 1: Find Unique Elements of the First Vector Using setdiff Function

Example 1 explains how to check which values are contained in one vector, but not in another vector using the setdiff function.

setdiff(vec1, vec2)           # Apply setdiff function
# 1 2 3 4 5

The RStudio console returns the values ranging from 1 to 5, i.e. those values are only contained in vec1, but not in vec2.


Example 2: Find Unique Elements of the First Vector Using %in%-Operator

The R programming language provides additional ways how to find values only contained in vector No. 1. In this Example, I’ll show how to find such elements using the %in%-operator. Have a look at the following R code:

vec1[! vec1 %in% vec2]        # Apply  %in%-operator
# 1 2 3 4 5

As you can see, the output is exactly the same as in Example 1. Looks good!


Video & Further Resources

Have a look at the following video of my YouTube channel. I’m explaining the contents of this article in the video:


The YouTube video will be added soon.


In addition, I can recommend to read the other tutorials on this homepage:


In summary: In this R tutorial you learned how to print those elements that are only contained in the first vector. In case you have additional questions, please let me know in the comments section.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.