How to get the combinations for a range of values with repetition in R?


The combination of values with repetition is the combination where the values can be repeated when creating the combination. For example, if we have three values say 1 and 2 then the combination of these values with repetition will be as follows −

1 1
2 1
1 2
2 2

For this purpose, we can use expand.grid function as shown in the below examples.

Example 1

 Live Demo

expand.grid(rep(list(1:2),2))

Output

  Var1 Var2
1  1   1
2  2   1
3  1   2
4  2   2

Example2

 Live Demo

expand.grid(rep(list(1:2),3))

Output

  Var1 Var2 Var3
1  1   1    1
2  2   1    1
3  1   2    1
4  2   2    1
5  1   1    2
6  2   1    2
7  1   2    2
8  2   2    2

Example3

 Live Demo

expand.grid(rep(list(1:2),4))

Output

  Var1 Var2 Var3 Var4
1  1   1    1    1
2  2   1    1    1
3  1   2    1    1
4  2   2    1    1
5  1   1    2    1
6  2   1    2    1
7  1   2    2    1
8  2   2    2    1
9  1   1    1    2
10 2   1    1    2
11 1   2    1    2
12 2   2    1    2
13 1   1    2    2
14 2   1    2    2
15 1   2    2    2
16 2   2    2    2

Example4

 Live Demo

expand.grid(rep(list(1:2),5))

Output

  Var1 Var2 Var3 Var4 Var5
1  1   1    1    1    1
2  2   1    1    1    1
3  1   2    1    1    1
4  2   2    1    1    1
5  1   1    2    1    1
6  2   1    2    1    1
7  1   2    2    1    1
8  2   2    2    1    1
9  1   1    1    2    1
10 2   1    1    2    1
11 1   2    1    2    1
12 2   2    1    2    1
13 1   1    2    2    1
14 2   1    2    2    1
15 1   2    2    2    1
16 2   2    2    2    1
17 1   1    1    1    2
18 2   1    1    1    2
19 1   2    1    1    2
20 2   2    1    1    2
21 1   1    2    1    2
22 2   1    2    1    2
23 1   2    2    1    2
24 2   2    2    1    2
25 1   1    1    2    2
26 2   1    1    2    2
27 1   2    1    2    2
28 2   2    1    2    2
29 1   1    2    2    2
30 2   1    2    2    2
31 1   2    2    2    2
32 2   2    2    2    2

Updated on: 16-Mar-2021

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements