[R] Permutations

F. Tusell etptupaf at bs.ehu.es
Wed Jul 14 09:19:45 CEST 2004


Jordi:

If I understand you well, the function below may do what you asked for.

It is not clear to me from your posting wether e.g.

   1 2 4   3 5 6   7 8 9    10 11 12

and

   1 4 2   3 5 6   7 8 9    10 11 12

should count as differente permutations, i.e., wether once one pair of 
elements interchange their
blocks, permutations within any block are allowable. I have assumed that 
only one pair of
elements are interchanged (but the function could be modified to account 
for other possibilities).

 > permutations
function(elements,blocks) {
    n <- length(elements)
    el.per.block <- n / blocks
    for (i in 1:n) {                    # For each element in turn,
      b <- floor(i/(el.per.block+.1))+1 # find which block it belongs to.
      if (b==blocks)                    # If in the last block, we are done.
        break
      allow.pos <- b*el.per.block + 1   # Find first position it could 
migrate to...
      for (j in (allow.pos:n)) {        # and create permutations with 
all allowable
        perm <- elements                # interchanges.
        perm[i] <- elements[j]
        perm[j] <- elements[i]
        print(perm)
      }
    }   
  }

 > permutations(1:4,2)
[1] 3 2 1 4
[1] 4 2 3 1
[1] 1 3 2 4
[1] 1 4 3 2
 > permutations(1:6,2)
[1] 4 2 3 1 5 6
[1] 5 2 3 4 1 6
[1] 6 2 3 4 5 1
[1] 1 4 3 2 5 6
[1] 1 5 3 4 2 6
[1] 1 6 3 4 5 2
[1] 1 2 4 3 5 6
[1] 1 2 5 4 3 6
[1] 1 2 6 4 5 3
 > permutations(1:9,3)
[1] 4 2 3 1 5 6 7 8 9
[1] 5 2 3 4 1 6 7 8 9
[1] 6 2 3 4 5 1 7 8 9
[1] 7 2 3 4 5 6 1 8 9
[1] 8 2 3 4 5 6 7 1 9
[1] 9 2 3 4 5 6 7 8 1
[1] 1 4 3 2 5 6 7 8 9
[1] 1 5 3 4 2 6 7 8 9
[1] 1 6 3 4 5 2 7 8 9
[1] 1 7 3 4 5 6 2 8 9
[1] 1 8 3 4 5 6 7 2 9
[1] 1 9 3 4 5 6 7 8 2
[1] 1 2 4 3 5 6 7 8 9
[1] 1 2 5 4 3 6 7 8 9
[1] 1 2 6 4 5 3 7 8 9
[1] 1 2 7 4 5 6 3 8 9
[1] 1 2 8 4 5 6 7 3 9
[1] 1 2 9 4 5 6 7 8 3
[1] 1 2 3 7 5 6 4 8 9
[1] 1 2 3 8 5 6 7 4 9
[1] 1 2 3 9 5 6 7 8 4
[1] 1 2 3 4 7 6 5 8 9
[1] 1 2 3 4 8 6 7 5 9
[1] 1 2 3 4 9 6 7 8 5
[1] 1 2 3 4 5 7 6 8 9
[1] 1 2 3 4 5 8 7 6 9
[1] 1 2 3 4 5 9 7 8 6

Notice that no error checking of any kind is done: one should check, 
e.g. that el.per.block is
integer.

Best,

ft.

-- 
Fernando TUSELL                                e-mail:
Departamento de Econometría y Estadística           etptupaf at bs.ehu.es 
Facultad de CC.EE. y Empresariales             Tel:   (+34)94.601.3733
Avenida Lendakari Aguirre, 83                  Fax:   (+34)94.601.3754
E-48015 BILBAO  (Spain)                        Secr:  (+34)94.601.3740




More information about the R-help mailing list