Vassilis Chasiotis
Vassilis Chasiotis

Reputation: 439

Permutations and combinations in R

I have N=4 elements and q=3 elements symboled as 1,2,3.

I create the matrix M, which contains all the vectors of N=4 elements with 2 elements equal to 1, 1 element equals to 2 and 1 element equals to 3 in all possible positions, using interpc as follows:

library(iterpc)
I=iterpc(c(2,1,1), labels=c(1,2,3), ordered=TRUE)
M=getall(I)
> M
      [,1] [,2] [,3] [,4]
 [1,]    1    1    2    3
 [2,]    1    1    3    2
 [3,]    1    2    1    3
 [4,]    1    2    3    1
 [5,]    1    3    1    2
 [6,]    1    3    2    1
 [7,]    2    1    1    3
 [8,]    2    1    3    1
 [9,]    2    3    1    1
 [10,]    3    1    1    2
 [11,]    3    1    2    1
 [12,]    3    2    1    1

I want a way in order to NOT create the rows 2, 5, 6, 10, 11 and 12.

These rows are connected with the others. For example, row 2 can be constructed by permutting the elements 2 and 3 of row 1. In the same way row 5 can be constructed using row 3.

So, is there any way just to construct the rows 1, 3, 4, 7, 8 and 9, but NOT the rows 2, 5, 6, 10, 11 and 12 ?

Upvotes: 1

Views: 162

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 146164

It sounds like you want to treat your 2s and 3s equivalently for permutations. Here's a solution that just uses 1s and 3s for the initial generation, and then goes through each row changing the first 3 to a 2:

library(iterpc)
I=iterpc(c(2,2), labels=c(1,3), ordered=TRUE)
M=getall(I)
t(apply(M, 1, function(x) {x[match(3, x)] = 2; x}))
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    2    3
# [2,]    1    2    1    3
# [3,]    1    2    3    1
# [4,]    2    1    1    3
# [5,]    2    1    3    1
# [6,]    2    3    1    1

Upvotes: 4

Related Questions