Home » How to Compare Two Vectors in R (With Examples)

How to Compare Two Vectors in R (With Examples)

by Erma Khan

You can use the following basic syntax to compare two vectors in R:

#check if two vectors are identical
identical(vector_1, vector_2)

#display items that are in both vectors
intersect(vector_1, vector_2)

#display items that are only in first vector, but not in second vector
setdiff(vector_1, vector_2)

The following examples show how to use this syntax in practice.

Example 1: Check if Two Vectors Are Identical

The following code shows how to use the identical() function to check if two vectors are identical:

#define vectors
vector_1 

#check if two vectors are identical
identical(vector_1, vector_2)

[1] FALSE

The two vectors are not identical, so a value of FALSE is returned.

Example 2: Find Items that Exist in Both Vectors

The following code shows how to use the intersect() function to display the items that exist in both vectors:

#define vectors
vector_1 

#display items that exist in both vectors
intersect(vector_1, vector_2)

[1] "Bob"  "Carl" "Doug"

The three items that exist in both vectors are displayed.

We can also use the length() function if we simply want to know how many items exist in both vectors:

#find how many items exist in both vectors
length(intersect(vector_1, vector_2))

[1] 3

Three items exist in both vectors.

Example 3: Find Items that Only Exist in One Vector

The following code shows how to use the setdiff() function to display the items that exist in the first vector, but not the second:

#define vectors
vector_1 

#display items that exist in first vector, but not in second vector
setdiff(vector_1, vector_2)

[1] "Andy"

Exactly one item exists in the first vector that does not exist in the second vector.

We can switch the two vectors around to identify the items that exist in the second vector, but not the first:

#define vectors
vector_1 

#display items that exist in second vector, but not in first vector
setdiff(vector_2, vector_1)

[1] "Ethan" "Fred"

Two items exist in the second vector that do not exist in the first.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Compare Two Columns in R
How to Compare Strings in R
How to Append Values to a Vector Using a Loop in R

Related Posts