Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

Can anyone tell me how to find the common elements from multiple vectors?

a <- c(1,3,5,7,9)

b <- c(3,6,8,9,10)

c <- c(2,3,4,5,7,9)

I want to get the common elements from the above vectors (ex: 3 and 9)

2 Answers

0 votes
by
edited by

To find the common elements from multiple vectors, you can use the intersect function from the sets base R package.

The basic syntax is given below:

intersect(x, y)

x, y

vectors (of the same mode) containing a sequence of items (conceptually) with no duplicate values.

Intersect will discard any duplicated values in the arguments, and they apply as. vectors to their arguments (and so, in particular, coerce factors to character vectors).

In your case:

a <- c(1,3,5,7,9)

b <- c(3,6,8,9,10)

c <- c(2,3,4,5,7,9)

> intersect(intersect(a,b),c)

[1] 3 9

OR

Reduce(intersect, list(a,b,c))

[1] 3 9

0 votes
by (2.8k points)
Different methodologies can be applied in computer science for finding the common features of many vectors (or arrays) across different programming languages.

Example vectors
A <- c(1,3,5,7,9)
B <- c(3,6,8,9,10)
C <- c(2,3,4,5,7,9)

Finding common elements

common_elements <- Reduce(intersect, list(A,B,C))

print(common_elements) # Print outputs common elements 3 9

One of the possible solutions for doing this is turning to sets or array functions (for example filter in JavaScript).

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...