How to find common elements from several vectors?

Can someone tell me how to find 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 common elements from the above vectors (for example: 3 and 9)

+85
vector r
Sep 12 '10 at 16:52
source share
3 answers

There may be a smarter way, but

 intersect(intersect(a,b),c) 

will do the job.

EDIT: smarter and more convenient if you have many arguments:

 Reduce(intersect, list(a,b,c)) 
+198
Sep 12 '10 at 17:00
source share

There is already a good answer, but there are several more ways to do this:

 unique(c[c%in%a[a%in%b]]) 

or,

 tst <- c(unique(a),unique(b),unique(c)) tst <- tst[duplicated(tst)] tst[duplicated(tst)] 

Obviously, you can omit unique calls if you know that there are no duplicate values ​​within a , b or c .

+11
Sep 13 '10 at 9:14
source share
 intersect_all <- function(a,b,...){ all_data <- c(a,b,...) require(plyr) count_data<- length(list(a,b,...)) freq_dist <- count(all_data) intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"] intersect_data } intersect_all(a,b,c) 

UPDATE IMAGE Simpler code

 intersect_all <- function(a,b,...){ Reduce(intersect, list(a,b,...)) } intersect_all(a,b,c) 
+1
May 27 '16 at 5:19
source share



All Articles