开发者

I want to generate n! permutations for a given n in R

suppose n=3 then开发者_运维知识库 output should be: a vector containing vectors: 123 213 132 231 321


This will solve your question:

install.packages("combinat")
require(combinat)
permn(1:3)

Also the functions: choose, combn ,expand.grid Might prove useful for you in the future.


library(gtools)
permutations(3,3)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1


The gregmisc package should have the permutations() function.

permutations3,3)


Here's some non-recursive code for this:

maxdepth <- 4
curdepth <- 1
l <- list()
i <- 0
while (i < maxdepth) {
    l <- c(l, 1)
    i <- i+1
}
done <- 0
results <- list()
resct <- 1

print(paste(sep=",",l))

while (curdepth > 0) {
    if (curdepth == maxdepth) {
        results[[resct]] <- l
        resct <- resct+1
        l[[curdepth]] <- l[[curdepth]]+1
    }
    if (l[[curdepth]] == maxdepth+1) {
        while (!done && l[[curdepth]] == maxdepth+1) {
            l[[curdepth]] <- 1
            curdepth <- curdepth-1
            if (curdepth == 0) {
                done <- 1
            }
        }
        if (!done) {
            l[[curdepth]] <- l[[curdepth]]+1
        }
    } else if (curdepth < maxdepth) {
        curdepth <- curdepth+1
    }
}

edit: made to output vector instead of printing; when done, "results" should contain the desired answer


I don't know if it is the case, but I'll give it a try.
If you'd like to do something with huge number of permutations of a bit longer vectors, it is much less demanding and about as good to use Monte Carlo and simply sample the space with large number of random permutations (that might be generated in R with sample function).


A while back I had to do this in base R without loading any packages:

permutations <- function(n){
    if(n==1){
        return(matrix(1))
    } else {
        sp <- permutations(n-1)
        p <- nrow(sp)
        A <- matrix(nrow=n*p,ncol=n)
        for(i in 1:n){
            A[(i-1)*p+1:p,] <- cbind(i,sp+(sp>=i))
        }
        return(A)
    }
}

Example:

> permutations(3)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜