how to do the systematic permutation in R?

Viewed 83

I have a vector including 9 observations and set to 3 treatments. I need to do the systematic permutation,not 9!. It is 9!/(2!3!4!)=1260. first 9 choose 2,then 7 choose 3, rest obs will in treatment 3. I have already write the code for 2 parts,but I can not figure out how to list all the possible outcomes. Since there are some observations are replicate. the permutation are not quite right. I need to assign the Id for each observation first. I have some problem about how to assign the id and permute id first, then return the real observations. list is my R code.there are some mistakes. I need a help to complete this program. Thank you!

for (k in 1260) {
  allperm<-c(A,B,C)
  A <- combn(complete, 2)
  for (i in 1:36){
    complete_B <- complete[!(complete %in% A[,i])]
    B <- combn(complete_B, 3)
    for (j in 1:35){
      C <- complete_B[!(complete_B %in% c(B[,j], A[,i]))]     
    }
  }
}
1 Answers

here is a base R solution to obtain all permutations allPerms as well as the partitions A,B and C

v <- 1:9
allPerms <- lapply(sapply(combn(v,2,simplify = FALSE), 
                          function(p) combn(v[-p],3,FUN = function(k) c(p,k),simplify = FALSE)),
                   function(k) c(k,v[-k]))

A <- lapply(allPerms, `[`,1:2)
B <- lapply(allPerms, `[`,3:5)
C <- lapply(allPerms, `[`,6:9)

such that

> head(allPerms)
[[1]]
[1] 1 2 3 4 5 6 7 8 9

[[2]]
[1] 1 2 3 4 6 5 7 8 9

[[3]]
[1] 1 2 3 4 7 5 6 8 9

[[4]]
[1] 1 2 3 4 8 5 6 7 9

[[5]]
[1] 1 2 3 4 9 5 6 7 8

[[6]]
[1] 1 2 3 5 6 4 7 8 9

> head(A)
[[1]]
[1] 1 2

[[2]]
[1] 1 2

[[3]]
[1] 1 2

[[4]]
[1] 1 2

[[5]]
[1] 1 2

[[6]]
[1] 1 2

> head(B)
[[1]]
[1] 3 4 5

[[2]]
[1] 3 4 6

[[3]]
[1] 3 4 7

[[4]]
[1] 3 4 8

[[5]]
[1] 3 4 9

[[6]]
[1] 3 5 6

> head(C)
[[1]]
[1] 6 7 8 9

[[2]]
[1] 5 7 8 9

[[3]]
[1] 5 6 8 9

[[4]]
[1] 5 6 7 9

[[5]]
[1] 5 6 7 8

[[6]]
[1] 4 7 8 9

If you want outputs in the format of matrix, you can try the code below

v <- 1:9
allPerms <- sapply(sapply(combn(v,2,simplify = FALSE), 
                          function(p) combn(v[-p],3,FUN = function(k) c(p,k),simplify = FALSE)),
                   function(k) c(k,v[-k]))

A <- allPerms[1:2,]
B <- allPerms[3:5,]
C <- allPerms[6:9,]
Related