R Program to find common elements from multiple vectors

How to find common elements from multiple vectors

Here we are explaining how to write an R program to find common elements from multiple vectors. Here we are using a built-in function intersect() for this. This function helps to find the common elements from multiple vectors. The syntax of this function is

intersect(x, y, …)

Here x, y are the vectors, data frames, or ps objects containing a sequence of elements whose common elements need to be found.

How to find common elements from multiple vectors in the R program

Below are the steps used in the R program to find common elements from multiple vectors. In this R program, we directly give the vectors to built-in functions. Here we are using variables A, B, C for holding vectors and variable inter for holding the result of intersection.

ALGORITHM

  • STEP 1: Assign variables A,B,C with vector values
  • STEP 2: First print original vector values
  • STEP 3: Call the function intersect as intersect(intersect(A,B),C)
  • STEP 4: Assign variable inter with the result of the intersection
  • STEP 5: print the variable inter holding result of the function

R Source Code

A = c(15, 10, 40, 20, 14, 25, 29, 15)
B = c(35, 20, 30, 40, 18, 35, 25, 14)
C = c(25, 30, 30, 20, 13, 25, 14, 17)

print("Original Vectors:")
## [1] "Original Vectors:"
print("A: ")
## [1] "A: "
print(A)
## [1] 15 10 40 20 14 25 29 15
print("B: ")
## [1] "B: "
print(B)
## [1] 35 20 30 40 18 35 25 14
print("C: ")
## [1] "C: "
print(C)
## [1] 25 30 30 20 13 25 14 17
print("Common elements from above vectors:")
## [1] "Common elements from above vectors:"
inter= intersect(intersect(A,B),C)

print(inter)
## [1] 20 14 25

R Source Code

A = c(150, 100, 400, 200, 140, 250, 290, 150)
B = c(350, 200, 300, 400, 150, 350, 250, 140)
C = c(250, 300, 300, 200, 130, 250, 150, 170)

print("Original Vectors:")
## [1] "Original Vectors:"
print("A: ")
## [1] "A: "
print(A)
## [1] 150 100 400 200 140 250 290 150
print("B: ")
## [1] "B: "
print(B)
## [1] 350 200 300 400 150 350 250 140
print("C: ")
## [1] "C: "
print(C)
## [1] 250 300 300 200 130 250 150 170
print("Common elements from above vectors:")
## [1] "Common elements from above vectors:"
inter= intersect(intersect(A,B),C)

print(inter)
## [1] 150 200 250