rhombidodecahedron
rhombidodecahedron

Reputation: 7922

Getting all combinations in R, repetition allowed

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?

Upvotes: 9

Views: 6516

Answers (3)

Gürol Canbek
Gürol Canbek

Reputation: 1156

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)

Upvotes: 1

mpalanco
mpalanco

Reputation: 13570

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")

Upvotes: 3

rhombidodecahedron
rhombidodecahedron

Reputation: 7922

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

Upvotes: 11

Related Questions