#The following functions will work. I have
not figured out how to remove the for loop in the apply statement
#The first function generates the “cycles”
needed. You can use it for generating all combinations as well as permutations.
#the second function generates the
permutation using a vector 1:n, that contains the “unused” values.
#Much better if programmed in C I agree. At
least the cycle generator is fast.
#this returns a matrix with each row
containing a pemutation
"gen.cycle" <-
function(x)
{
x <- x + 1
t(apply(cbind(x, cumprod(x),
rev(cumprod(rev(x)))), 1, function(x)
{
rep(rep(1:x[1],
each = x[2]/x[1]), x[3]/x[1])
}
) - 1)
}
make.perm<-function(n,values=n)
{
w<-gen.cycle((n-1):0)+1
ww<-apply(w,2,function(x,n1,values)
{
start<-n1
for(i in n1)
{
x[i]<-start[x[i]]
start<-start[start!=x[i]]
}
values[x]
},n1=1:n,values=values)
t(ww)
}
make.perm(3,values=c("a","b","c"))
[,1] [,2] [,3]
[1,] "a" "b"
"c"
[2,] "b" "a"
"c"
[3,] "c" "a"
"b"
[4,] "a" "c"
"b"
[5,] "b" "c"
"a"
[6,] "c" "b"
"a"
From:
s-news-owner@lists.biostat.wustl.edu
[mailto:s-news-owner@lists.biostat.wustl.edu] On
Behalf Of Reyderman, Larisa
Sent: Thursday, April 14, 2005
2:54 PM
To:
's-news@lists.biostat.wustl.edu'
Subject: [S] permutation
Dear
All,
I
have a seemingly easy question. I need to create a matrix consisting of
all possible permutations of the following vector:
0.5 1.0 1.5 2.0 3.0 4.0
5.0 6.0 8.0 10.0 12.0 16.0
I
know that "sample" function with (replace=F) will generate a
permutation, however, I need all possible permutations.
Thank
you for your help.
Larisa
*********************************************************************
This message and any attachments are solely for the intended recipient. If you
are not the intended recipient, disclosure, copying, use or distribution of the
information included in this message is prohibited -- Please immediately and
permanently delete.