R: unshared elements across multiple vectors (opposite to intersect)

Viewed 998

I want to extract all the shared elements and unshared elements between multiple vectors.

Say I have these vectors:

set.seed(9)
a <- sample(LETTERS,10,replace=F)
b <- sample(LETTERS,10,replace=F)
c <- sample(LETTERS,10,replace=F)

I first explore their overlap with a Venn diagram:

venn.diagram(list('a'=a,'b'=b,'c'=c), filename="test.png", height=1000, width=1000, imagetype="png", units="px")

test

I know how to obtain the elements shared by all the vectors (the central 3), this way:

shared <- Reduce(intersect, list(a,b,c))
length(shared)#3, correct

However, how can I obtain the unshared elements across the groups (5+7+5=17)?

My attempt is the following:

outersect <- function(a,b) unique(c(setdiff(a,b), setdiff(b,a)))
unshared <- Reduce(outersect, list(a,b,c))
length(unshared)#20, I expect 17 (5+7+5)

But the number is incorrect, since comparisons are made on a pairwise basis... Any idea to do this easily?

2 Answers
Related