Skip to content
Prev 173708 / 398502 Next

permutations in R

Try this:
+ function (n, r, v = 1:n)
+ {
+    if (r == 1)
+       matrix(v, n, 1)
+    else if (n == 1)
+       matrix(v, 1, r)
+    else {
+       X <- NULL
+       for (i in 1:n) X <- rbind(X, cbind(v[i], fn_perm_list(n -
+            1, r - 1, v[-i])))
+        X
+    }
+ }
[,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1

Note that the you can use library gregmisc without using this
function, but I thought it might be instructive for you to see how
this is done.

Here's how you would normally do this:
[,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1

Cheers,
Dan Viar
On Fri, Mar 13, 2009 at 8:06 PM, onyourmark <william108 at gmail.com> wrote: