Skip to content
Prev 206321 / 398506 Next

Fixed size permutations

Nick Fankhauser wrote:
Looks to me like you're just doing expand.grid, but without
the 'all variables equal' cases. If that's correct and if
n > 1, then this might do it:

bag <- function(n,K){
   L <- vector(mode='list', length=K)
   L <- lapply(L, function(x) {x <- seq_len(n)})
   d <- expand.grid(L)
   keeprow <- apply(d, 1, function(x) {var(x)!=0})
     ## I'm blanking out on a better way to test for equal values
   td <- t(as.matrix(d[keeprow,]))
   dimnames(td) <- c(NULL, NULL)
   rtd <- td[nrow(td):1,]
   rtd
}
all.equal(bag(5,2), bag2(5))
#[1] TRUE

all.equal(bag(9,3), bag3(9))
#[1] TRUE

  -Peter Ehlers