如何生成矩阵来存储集合的所有非空子集

时间:2013-10-28 23:20:48

标签: r matrix while-loop subset

假设我有一个N = {1,2,3}的集合,那么我们可以列出它的所有7个非空子集。

    n=3 # number of elements in a set
    a=2^n-1 # number of non-empty subsets for that set
    subsets=lapply(1:n, function(x) combn(n, x)) # list all the non-empty subest
    subsets

现在我想将这些子集放入矩阵中并组织如下:

    if n=3     or in an index matrix:    
    1 0 0      1 0 0
    0 2 0      0 1 0
    0 0 3      0 0 1

    1 2 0      1 1 0
    1 0 3      1 0 1
    0 2 3      0 1 1

    1 2 3      1 1 1

任何人都知道如何编写可以轻松扩展到任何n(= 4,5,6 ...)的代码?我试过这个:

    subindex=matrix(c(0), nrow=a, ncol=n)

    i=1
      while(i<=a){

       j=n
       b=2^(n-1)
       N=i
          while(N>0){
             if(b<=N) {subindex[i,j]=1}&{N=N-b}
             b=trunc(b/2)
             j=j-1
          }

       i=i+1
       }
      subindex

但是我得到的索引矩阵在第3行和第4行中是错误的。如果n = 4,那么还有更多错误......任何人都能纠正这个或简化这段代码吗?或者只是写一个全新的代码。真的很感激。

1 个答案:

答案 0 :(得分:3)

n <- 4
lapply(seq_len(n), function(i)t(combn(n, i, FUN = tabulate, nbins = n)))

# [[1]]
#      [,1] [,2] [,3] [,4]
# [1,]    1    0    0    0
# [2,]    0    1    0    0
# [3,]    0    0    1    0
# [4,]    0    0    0    1
# 
# [[2]]
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    0    0
# [2,]    1    0    1    0
# [3,]    1    0    0    1
# [4,]    0    1    1    0
# [5,]    0    1    0    1
# [6,]    0    0    1    1
# 
# [[3]]
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    1    0
# [2,]    1    1    0    1
# [3,]    1    0    1    1
# [4,]    0    1    1    1
# 
# [[4]]
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    1    1