I wrote an article in the July 2016 issue of MSDN Magazine titled “Permutations using R”. See https://visualstudiomagazine.com/articles/2016/07/01/permutations-using-r.aspx.

A mathematical permutation of order n is one possible arrangement of n items. In R the items are the integers 1 through n, so one permutation of order n = 5 is (2, 5, 1, 4, 3).

The R language does not come with built-in functions to work with permutations. In my article I show how to code these from scratch. The key functions are perm_init() to create a first permutation like (1, 2, 3, 4), and perm_succ() to generate the successor to a given permutation.

Here’s example code that generates all 4! = 4 * 3 * 2 * 1 = 24 permutation elements for order n = 4:

n = as.integer(4)
p = perm_init(n)
i = as.integer(1)
while (is.null(p) == FALSE) {
cat(formatC(i, digits=2), " ")
perm_display(p)
p = perm_succ(p)
i = i + 1
}

I implemented the permutation code using simple R language lists. An alternative would have been to implement the code as an S3 class, or an S4 class, or an RC class — it’s somewhat annoying that R has multiple ways to implement OOP.

### Like this:

Like Loading...

*Related*