开发者

Is there an expand.grid like function in R, returning permutations?

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  开发者_JS百科   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.


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))


Try ?allPerms in the vegan package.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜