R获得N个变量的所有可能组合的所有公共元素

时间:2017-03-08 08:59:58

标签: r combinations

我想在n个变量的所有可能组合中获得所有共同元素。

假设我们有3个变量:a,b和c,每个变量有4个,2个和3个元素。我想在列(a,b,c,ab,ac,bc和abc)中创建一个包含所有可能组合的数据框,并在第二列中创建公共元素。例如:

输入:

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

我想要一个类似于:

的输出
   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" 

到目前为止,我试过这个:

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))

1 个答案:

答案 0 :(得分:4)

很多方法,一个是:

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)

输出:

      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