Combination without repetition in R

11,369

Solution 1

Try something like:

x <- c("a","b","c","d","e")
d1 <- combn(x,3) # All combinations

d1 

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] "a"  "a"  "a"  "a"  "a"  "a"  "b"  "b"  "b"  "c"  
# [2,] "b"  "b"  "b"  "c"  "c"  "d"  "c"  "c"  "d"  "d"  
# [3,] "c"  "d"  "e"  "d"  "e"  "e"  "d"  "e"  "e"  "e"

nrow(unique(t(d1))) == nrow(t(d1))
# [1] TRUE

d2 <- expand.grid(x,x,x) # All permutations 

d2

#     Var1 Var2 Var3
# 1      a    a    a
# 2      b    a    a
# 3      c    a    a
# 4      d    a    a
# 5      e    a    a
# 6      a    b    a
# 7      b    b    a
# 8      c    b    a
# 9      d    b    a
# ...

nrow(unique(d2)) == nrow(d2)
# [1] TRUE

Solution 2

try this

x <- c("a","b","c","d","e")
expand.grid(rep(list(x), 3))
Share:
11,369
Error404
Author by

Error404

Updated on June 11, 2022

Comments

  • Error404
    Error404 almost 2 years

    I am trying to get all the possible combinations of length 3 of the elements of a variable. Although it partly worked with combn() I did not quite get the output I was looking for. Here's my example

    x <- c("a","b","c","d","e")
    t(combn(c(x,x), 3)) 
    

    The output I get looks like this

           [,1] [,2] [,3]
      [1,] "a"  "b"  "c" 
      [2,] "a"  "b"  "d" 
      [3,] "a"  "b"  "e" 
    

    I am not really happy with this command for 2 reasons. I wanted to get an output that says "a+b+c" "a+b+b"...., unfortunately I wasn't able to edit the output with paste() or something.

    I was also looking forward for one combination of each set of letters, that is I either get "a+b+c" or "b+a+c" but not both.