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.
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.
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
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:")
print("A: ")
print(A)
print("B: ")
print(B)
print("C: ")
print(C)
print("Common elements from above vectors:")
inter= intersect(intersect(A,B),C)
print(inter)
[1] "Original Vectors:" [1] "A: " [1] 15 10 40 20 14 25 29 15 [1] "B: " [1] 35 20 30 40 18 35 25 14 [1] "C" [1] 25 30 30 20 13 25 14 17 [1] "Common elements from above vectors:" [1] 20 14 25