tags:

views:

125

answers:

2

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)

+8  A: 

There might be a cleverer way to go about this, but

intersect(intersect(a,b),c)

will do the job.

EDIT: More cleverly, and more conveniently if you have a lot of arguments:

Reduce(intersect, list(a,b,c))
bnaul
I have several arguments, so the second option will do the job for me.
Chares
+3  A: 

A good answer already, but there are a couple of other 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)]

You can obviously omit the unique calls if you know that there are no repeated values within a, b or c.

James
Thank you James for the alternative ways!!
Chares
No problem. Note that there were a couple of errors in my original formulation, I've edited them so they work properly now.
James
@James None of this solutions gives correct answer. Check for example data.
Marek
@Marek Yes, I was too quick to post orginally! See comment above.
James
@James I wrote comment in the same moment when you correct answer. Now it's ok, but I can't undo downvote. If you do some edit (e.g. spelling from "you no that" to "you know that") then I undo.
Marek
@Marek Done that now thanks. Hopefully there are no more mistakes in it! ;)
James