Open In App

How to find common elements from multiple vectors in R ?

Last Updated : 21 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to find the common elements from multiple vectors in R Programming Language.

To do this intersect() method is used. It is used to return the common elements from two objects.

Syntax: intersect(vector1,vector2)

where, vector is the input data.

If there are more than two vectors then we can combine all these vectors into one except one vector. Those combined vectors are passed as one argument and that remaining vector is passed as second argument.

Syntax: intersect(c(vector1,vector2,…,vector n),vector_m)

Example 1: R program to create two vectors and find the common elements.

So we are going to create a vector with elements.

R




# create vector b
b = c(2, 3, 4, 5, 6, 7)
  
# create vector a
a = c(1, 2, 3, 4)
  
# combine both the vectors
print(intersect(b, a))


Output:

[1] 2 3 4 

Example 2: R program to find common elements in two-character data.

We are taking two vectors which contain names and find the common elements.

R




# create vector b
b = c("sravan", "gajji", "gnanesh")
  
# create vector a
a = c("sravan", "ojaswi", "gnanesh")
  
# combine both the vectors
print(intersect(b, a))


Output:

[1] "sravan" "gnanesh"

Example 3: Find common elements from multiple vectors in R.

So we are combining b and a first, and they are passed as the first argument in intersect function and then pass the d vector as the second argument.

R




# create vector b
b = c(1, 2, 3, 4, 5)
  
# create vector a
a = c(3, 4, 5, 6, 7)
  
# create vector d
d = c(5, 6, 7, 8, 9)
  
# combine both the vectors b and a as 1 
# then combine with d
print(intersect(c(b, a), d))


Output:

[1] 5 6 7


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads