Re: [R] Multiset Permutations

From: G. Jay Kerns <gkerns_at_ysu.edu>
Date: Sun, 06 Apr 2008 19:27:39 -0400

Dear Steven,

The prob package does this, too. (Please see the * fix below).

x <- c(0, 0, 1, 2, 2)
library(prob)

A <- permsn(x, 5)                      # with repeated columns
B <- unique( data.frame( t(A) )) # no repeated rows

The data frame B will have 56 rows and 5 columns. If you need the columns collapsed, then you can use the

apply(B, 1, paste, sep = "", collapse = "")

command that Johannes suggested. Details are in the prob package vignette,

vignette("prob")

I hope that this helps,
Jay

permsn <- function (x, m)
{

    require(combinat)
    if (is.numeric(x) && length(x) == 1 && x > 0 && trunc(x) == x)

        x <- seq(x)
    temp <- combn(x, m)
    if ( isTRUE(all.equal(m,1)) ) {

        P <- temp
    } else if (isTRUE(all.equal(m, length(x)))) {

        temp <- matrix(x, ncol = 1)
        P <- array(unlist(permn(temp[, 1])), dim = c(m, factorial(m)))
    } else {
        k <- dim(temp)[1]
        n <- dim(temp)[2]
        P <- array(unlist(permn(temp[, 1])), dim = c(k, factorial(k)))
        for (i in 2:n) {
            a <- temp[, i]
            perms <- array(unlist(permn(a)), dim = c(k, factorial(k)))
            P <- cbind(P, perms)
        }

    }
    return(P)
}

G. Jay Kerns, Ph.D.
Assistant Professor / Statistics Coordinator Department of Mathematics & Statistics
Youngstown State University
Youngstown, OH 44555-0002 USA
Office: 1035 Cushwa Hall
Phone: (330) 941-3310 Office (voice mail)
-3302 Department
-3170 FAX
E-mail: gkerns_at_ysu.edu
http://www.cc.ysu.edu/~gjkerns/

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sun 06 Apr 2008 - 23:31:06 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 07 Apr 2008 - 00:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive