I have N=6
elements and q=3
elements symboled as 0
,1
,2
.
I want to create all the vectors of N=6
elements with 2
elements equal to 0
, 2
elements equal to 1
and 2
elements equal to 2
in all the possible positions.
The number of these vectors are equal to combn(6,2)*combn(4,2)*combn(2,2)=90
.
Here is a code that construct these 90
vectors in the matrix F
:
N=6
x<-c(1:N)
#########################################
A<-combn(x,2)
B<-matrix(0,ncol(A),length(x))
for( i in 1:ncol(A) )
{
y<-rep(0,N)
y[A[1:nrow(A),i]]<-1
B[i,]<-y
}
######################################
E<-matrix(0,nrow(B),length(x)-nrow(A))
for( i in 1:nrow(B) )
{
q=0
for( j in 1:ncol(B) )
{
if( B[i,j]!=1 )
{
q=q+1
E[i,q]<-j
}}}
########################################
ASD<-combn(E[i,],2)
F<-matrix(0,nrow(B)*ncol(ASD),length(x))
q=0
for( i in 1:nrow(B) )
{
ASD<-combn(E[i,],2)
for( j in 1:ncol(ASD) )
{
B[i,ASD[1:nrow(ASD),j]]<-2
q=q+1
F[q,]<-B[i,]
B[i,ASD[1:nrow(ASD),j]]<-0
}}
Is there any other less complicated way to do it?
You can use the iterpc
package:
> library(iterpc)
> I <- iterpc(c(2,2,2), labels=c(0,1,2), ordered=TRUE)
> getall(I)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 1 1 2 2
[2,] 0 0 1 2 1 2
[3,] 0 0 1 2 2 1
[4,] 0 0 2 1 1 2
[5,] 0 0 2 1 2 1
[6,] 0 0 2 2 1 1
[7,] 0 1 0 1 2 2
[8,] 0 1 0 2 1 2
[9,] 0 1 0 2 2 1
[10,] 0 1 1 0 2 2
[11,] 0 1 1 2 0 2
[12,] 0 1 1 2 2 0
[13,] 0 1 2 0 1 2
[14,] 0 1 2 0 2 1
[15,] 0 1 2 1 0 2
[16,] 0 1 2 1 2 0
[17,] 0 1 2 2 0 1
[18,] 0 1 2 2 1 0
[19,] 0 2 0 1 1 2
[20,] 0 2 0 1 2 1
[21,] 0 2 0 2 1 1
[22,] 0 2 1 0 1 2
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