Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all combinations in R, repetition allowed

Tags:

r

combinations

The built-in combn only gives half the combinations:

> t(combn(1:5, 2))
      [,1] [,2]
 [1,]    1    2
 [2,]    1    3
 [3,]    1    4
 [4,]    1    5
 [5,]    2    3
 [6,]    2    4
 [7,]    2    5
 [8,]    3    4
 [9,]    3    5
[10,]    4    5

For example there is no (1,1) nor (2,1).

How can I get all combinations?

like image 211
rhombidodecahedron Avatar asked Jul 18 '15 14:07

rhombidodecahedron


3 Answers

As @akrun said, it looks like expand.grid will do it.

> expand.grid(rep(list(1:5), 2))
   Var1 Var2
1     1    1
2     2    1
3     3    1
4     4    1
5     5    1
6     1    2
7     2    2
8     3    2
9     4    2
10    5    2
11    1    3
12    2    3
13    3    3
14    4    3
15    5    3
16    1    4
17    2    4
18    3    4
19    4    4
20    5    4
21    1    5
22    2    5
23    3    5
24    4    5
25    5    5
like image 194
rhombidodecahedron Avatar answered Oct 05 '22 02:10

rhombidodecahedron


You could get the Cartesian product using merge:

merge(1:5, 1:5)

Output:

   x y
1  1 1
2  2 1
3  3 1
4  4 1
5  5 1
6  1 2
7  2 2
8  3 2
9  4 2
10 5 2
11 1 3
12 2 3
13 3 3
14 4 3
15 5 3
16 1 4
17 2 4
18 3 4
19 4 4
20 5 4
21 1 5
22 2 5
23 3 5
24 4 5
25 5 5

Using sqldf:

df1 <- data.frame(a = 1:5)
df2 <- df1
sqldf("SELECT df1.a, df2.a FROM df1 
      CROSS JOIN df2")
like image 23
mpalanco Avatar answered Oct 05 '22 02:10

mpalanco


This is actually called as permutations with repeated elements. Besides the given recommendations, you can use gtools::permutations function:

gtools::permutations(5, 2, 1:5, repeats.allowed=TRUE)
like image 34
Gürol Canbek Avatar answered Oct 05 '22 02:10

Gürol Canbek