[R] exhaustive permutations

Jim Lemon bitwrit at ozemail.com.au
Wed Jan 16 11:27:20 CET 2002


Nick Bond wrote:

> ...However, where sample sizes are small, it is more appropriate (I think)
> to exhaustively calculate all possible permutations.  This is equivalent
> to determining all possible ways of assigning n samples to each of k
> groups = (kn)!/[(n!)^k*k!].

Perhaps this will do the job.

Jim


-------------- next part --------------
insert.value<-function(vec,newval,pos) {
 if(pos == 1) return(c(newval,vec))
 lvec<-length(vec)
 if(pos > lvec) return(c(vec,newval))
 return(c(vec[1:pos-1],newval,vec[pos:lvec]))
}

permute<-function(elem) {
 if(!missing(elem)) {
  if(length(elem) == 2) return(matrix(c(elem,elem[2],elem[1]),nrow=2))
  last.matrix<-permute(elem[-1])
  dim.last<-dim(last.matrix)
  new.matrix<-matrix(0,nrow=dim.last[1]*(dim.last[2]+1),ncol=dim.last[2]+1)
  for(row in 1:(dim.last[1])) {
   for(col in 1:(dim.last[2]+1))
    new.matrix[row+(col-1)*dim.last[1],]<-insert.value(last.matrix[row,],elem[1],col)
  }
  return(new.matrix)
 }
 else cat("Usage: permute(elem)\n\twhere elem is a vector\n")
}


More information about the R-help mailing list