R 如何生成矩阵来存储集合的所有非空子集
假设我有一个集合N={1,2,3},那么我们可以列出它的所有7个非空子集R 如何生成矩阵来存储集合的所有非空子集,r,matrix,while-loop,subset,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 现在我想把这些子集放入一个矩阵中,组织如下:
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
subindex=matrix(c(0),nrow=a,ncol=n)
i=1
while(i0){
如果(bn downvote)看起来有点不合理,不是吗?是的。我想我是在高速公路上偶然做的。现在它不会让我倒车了。我能说什么…@~~~Orz…感激和崇拜地流泪。非常感谢@flodel
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