Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination without repetition in R

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.

like image 327
Error404 Avatar asked Jan 24 '14 17:01

Error404


People also ask

What is the formula for combinations without repetition?

The number of k-element combinations of n objects, without repetition is Cn,k = (n k ) = n! k!( n − k)! . The counting problem is the same as the number of ways of putting k identical balls into n distinct boxes, such that each box receives at most one ball.

How do you make a combination in R?

combn() method in R language belonging to this package is used to generate all combinations of the elements of x taken m at a time. If x is a positive integer, returns all combinations of the elements of seq(x) taken m at a time. Syntax: combn(x, m, fun=NULL, simplify=TRUE, …)

What does Combn do in R?

The combn() function in R is used to return the combination of the elements of a given argument x taken m at a time.

How do you find the number of possible combinations?

The number of combinations of n objects taken r at a time is determined by the following formula: C(n,r)=n! (n−r)!


2 Answers

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
like image 177
Brandon Bertelsen Avatar answered Nov 02 '22 12:11

Brandon Bertelsen


try this

x <- c("a","b","c","d","e")
expand.grid(rep(list(x), 3))
like image 29
Salem Gharbi Avatar answered Nov 02 '22 13:11

Salem Gharbi