Mark
Mark

Reputation: 1769

Intersection of pairs of sets (any possible combination)

I have more than theree sets, but here I wrote the following example.

S1<-c("Frizzy","Jack","Amy")
S2<-c("Alice","Samy","Anna","Jack")
S3<-c("Frizzy","Anna","Fred","Jack")

I would like to obtain the following result

length(intersect(S1,S2))+length(intersect(S1,S3))+length(intersect(S2,S3))

without write manually all the possible combinations.

Upvotes: 1

Views: 141

Answers (1)

akrun
akrun

Reputation: 887008

We can use combn to get the pairwise intersect between the elements, get the lengths of the list elements and find the sum

sum(lengths(combn(list(S1, S2, S3), 2,
      FUN = function(x) Reduce(intersect, x), simplify = FALSE)))
#[1] 5

If there are many objects of the same pattern 'S' followed by some digits, use mget to get those all into a list instead of writing them manually

lst1 <- mget(ls(pattern = '^S\\d+$'))
sum(lengths(combn(lst1, 2, 
     FUN = function(x) Reduce(intersect, x), simplify = FALSE)))
#[1] 5

Upvotes: 2

Related Questions