aspire57
aspire57

Reputation: 1547

R get all common elements for all possible combinations of N variables

I would like to get all the common elements within all the possible combinations of n variables.

Let's say we have 3 variables: a, b and c, with 4, 2 and 3 elements each. I will like to create a data frame with all possible combinations in a column (a,b,c,ab,ac,bc and abc) and the common elements in a second column. Example:

input:

a<-c("x1","x2","x3","x4")
b<-c("x2","x5")
c<-c("x3","x4","x6")

I will like an output that looks something like:

   name       elements
1    a       "x1","x2","x3","x4"
2    b       "x2","x3","x5"
3    c       "x3","x4","x6"
4   ab       "x1","x2","x3","x4","x5"
5   ac       "x1","x2","x3","x4","x6"
6   bc       "x2","x3","x4","x5","x6"
7   abc      "x1","x2","x3","x4","x5","x6" 

So far I tried this:

all1<-c("a","b","c")
all2<-list(a,b,c)
all3<-c(a,b,c)

sapply (  1:3, function(x) combn(all1,x))
sapply (  1:3, function(x) combn(all2,x))
sapply (  1:3, function(x) combn(all3,x))

Upvotes: 2

Views: 104

Answers (1)

thc
thc

Reputation: 9705

Lots of ways, here's one:

grid <- expand.grid(a=c(T,F), b=c(T,F), c=c(T,F))
grid$results <- mapply(function(x,y,z) {
    unique(c(if(x) a,if(y) b,if(z) c))
},grid$a,grid$b,grid$c)

Output:

      a     b     c                results
1  TRUE  TRUE  TRUE x1, x2, x3, x4, x5, x6
2 FALSE  TRUE  TRUE     x2, x5, x3, x4, x6
3  TRUE FALSE  TRUE     x1, x2, x3, x4, x6
4 FALSE FALSE  TRUE             x3, x4, x6
5  TRUE  TRUE FALSE     x1, x2, x3, x4, x5
6 FALSE  TRUE FALSE                 x2, x5
7  TRUE FALSE FALSE         x1, x2, x3, x4
8 FALSE FALSE FALSE                   NULL

Upvotes: 4

Related Questions