views:

114

answers:

2

to become more specific, here is an example:

> expand.grid(5, 5, c(1:4,6),c(1:4,6))
   Var1 Var2 Var3 Var4
1     5    5    1    1
2     5    5    2    1
3     5    5    3    1
4     5    5    4    1
5     5    5    6    1
6     5    5    1    2
7     5    5    2    2
8     5    5    3    2
9     5    5    4    2
10    5    5    6    2
11    5    5    1    3
12    5    5    2    3
13    5    5    3    3
14    5    5    4    3
15    5    5    6    3
16    5    5    1    4
17    5    5    2    4
18    5    5    3    4
19    5    5    4    4
20    5    5    6    4
21    5    5    1    6
22    5    5    2    6
23    5    5    3    6
24    5    5    4    6
25    5    5    6    6

This data frame was created from all combinations of the supplied vectors. I would like to create a similar data frame from all permutations of the supplied vectors. Notice that each row must contain exactly 2 fives, yet not necessarily the fist two in line. Thank you.

A: 

Try ?allPerms in the vegan package.

Richie Cotton
+2  A: 

The code below works. (relies on permutations from gtools)

comb <- t(as.matrix(expand.grid(5, 5, c(1:4,6),c(1:4,6))))
perms <- t(permutations(4,4))
ans <- apply(comb,2,function(x) x[perms])
ans <- unique(matrix(as.vector(ans), ncol = 4, byrow = TRUE))
John
Excellent! I find it strange that there is not such a function built in
Brani