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
b = c (2, 3, 4, 5, 6, 7)
a = c (1, 2, 3, 4)
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
b = c ( "sravan" , "gajji" , "gnanesh" )
a = c ( "sravan" , "ojaswi" , "gnanesh" )
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
b = c (1, 2, 3, 4, 5)
a = c (3, 4, 5, 6, 7)
d = c (5, 6, 7, 8, 9)
print ( intersect ( c (b, a), d))
|
Output:
[1] 5 6 7