[R] Multiset Permutations
G. Jay Kerns
gkerns at ysu.edu
Mon Apr 7 01:27:39 CEST 2008
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
* fix: As it happens, your particular question helped to identify a
bug in the current CRAN version of prob. Thank you! :-) Below is a
fix until the updated version appears.
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/
More information about the R-help
mailing list