w3resource

R Programming: Find Common elements from multiple Vectors


Write a R program to find common elements from multiple vectors.

Sample Solution :

R Programming Code :

# Define the first vector
x = c(10, 20, 30, 20, 20, 25, 29, 26)

# Define the second vector
y = c(10, 50, 30, 20, 20, 35, 19, 56)

# Define the third vector
z = c(10, 40, 30, 20, 20, 25, 49, 26)

# Print a message indicating the start of displaying original vectors
print("Original Vectors:")

# Print the first vector
print("x: ")
print(x)

# Print the second vector
print("y: ")
print(y)

# Print the third vector
print("z: ")
print(z)

# Print a message indicating the start of displaying common elements
print("Common elements from above vectors:")

# Find the common elements among all three vectors
result = intersect(intersect(x,y),z)

# Print the common elements
print(result)

Output:

[1] "Original Vectors:"
[1] "x: "
[1] 10 20 30 20 20 25 29 26
[1] "y: "
[1] 10 50 30 20 20 35 19 56
[1] "z: "
[1] 10 40 30 20 20 25 49 26
[1] "Common elements from above vectors:"
[1] 10 20 30                         

Explanation:

  • Define Vectors:
    • x = c(10, 20, 30, 20, 20, 25, 29, 26): Creates a vector x with 8 integer elements.
    • y = c(10, 50, 30, 20, 20, 35, 19, 56): Creates a vector y with 8 integer elements.
    • z = c(10, 40, 30, 20, 20, 25, 49, 26): Creates a vector z with 8 integer elements.
  • Print Original Vectors:
    • print("Original Vectors:"): Prints a header indicating that the following output will be the original vectors.
    • print("x: "): Prints the label "x: ".
    • print(x): Displays the contents of vector x.
    • print("y: "): Prints the label "y: ".
    • print(y): Displays the contents of vector y.
    • print("z: "): Prints the label "z: ".
    • print(z): Displays the contents of vector z.
  • Find Common Elements:
    • print("Common elements from above vectors:"): Prints a header indicating that the following output will be the common elements.
    • result = intersect(intersect(x, y), z): Finds common elements between vectors x, y, and z. The intersect function is used twice: first to find common elements between x and y, and then between the result and z.
    • print(result): Displays the common elements found in all three vectors.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to find nth highest value in a given vector.
Next: Write a R program to convert given dataframe column(s) to a vector.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.