R Question Number of unique combinations A, A, A, A, B, B, B, B, B

I am trying to find a way to get a list from R of all possible unique permutations A, A, A, A, B, B, B, B, B.

Combinations were what were initially thought to be the method of obtaining the solution, so the answers are combinations.

+5
source share
2 answers

I think this is what you need. @bill was at the ball with a recommendation to combine uniqueand combn. We will also use the apply family to generate ALL combinations. Since it uniqueremoves duplicate rows, we need to wrap the results from combnto uniquethem. Then we transfer them back before returning to the screen so that each column represents a unique answer.

#Daters
x <- c(rep("A", 4), rep("B",5))
#Generates a list with ALL of the combinations
zz <- sapply(seq_along(x), function(y) combn(x,y))
#Filter out all the duplicates
sapply(zz, function(z) t(unique(t(z))))

What returns:

[[1]]
     [,1] [,2]
[1,] "A"  "B" 

[[2]]
     [,1] [,2] [,3]
[1,] "A"  "A"  "B" 
[2,] "A"  "B"  "B" 

[[3]]
     [,1] [,2] [,3] [,4]
[1,] "A"  "A"  "A"  "B" 
[2,] "A"  "A"  "B"  "B" 
[3,] "A"  "B"  "B"  "B" 

...

EDIT Since the question is about permutations, not combinations, the answer above is not so useful. This post describes a function to create unique permutations based on a set of parameters. I have no idea if it can be improved, but here one approach uses this function:

fn_perm_list <-
 function (n, r, v = 1:n)
 {
    if (r == 1)
       matrix(v, n, 1)
    else if (n == 1)
       matrix(v, 1, r)
    else {
       X <- NULL
       for (i in 1:n) X <- rbind(X, cbind(v[i], fn_perm_list(n -
            1, r - 1, v[-i])))
        X
    }
 } 

zz <- fn_perm_list(9, 9)

#Turn into character matrix. This currently does not generalize well, but gets the job done
zz <- ifelse(zz <= 4, "A", "B")

#Returns 126 rows as indicated in comments
unique(zz)
+3
source

, . ( , ): 4 A 5 B, 4 A 9 . . :

x <- rep('B',9) # vector of 9 B's

a_pos <- combn(9,4) # all possible ways to place 4 A among 9 positions

perms <- apply(a_pos, 2, function(p) replace(x,p,'A')) # all desired permutations

9x126 perms 4 A 5 B:

> dim(perms)
[1]   9 126
> perms[,1:4] ## look at first few columns
      [,1] [,2] [,3] [,4]
 [1,] "A"  "A"  "A"  "A" 
 [2,] "A"  "A"  "A"  "A" 
 [3,] "A"  "A"  "A"  "A" 
 [4,] "A"  "B"  "B"  "B" 
 [5,] "B"  "A"  "B"  "B" 
 [6,] "B"  "B"  "A"  "B" 
 [7,] "B"  "B"  "B"  "A" 
 [8,] "B"  "B"  "B"  "B" 
 [9,] "B"  "B"  "B"  "B" 
+2

All Articles