Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expand.grid with unknown set of variables

Tags:

r

So, expand.grid returns a df of all the combinations of the vectors passed.

df <- expand.grid(1:3, 1:3)
df <- expand.grid(1:3, 1:3, 1:3)

What I would like is a generalized function that takes 1 parameter (number of vectors) and returns the appropriate data frame.

combinations <- function(n) {
    return(expand.grid(0, 1, ... n))
}

Such that

combinations(2) returns(expand.grid(1:3, 1:3))
combinations(3) returns(expand.grid(1:3, 1:3, 1:3))
combinations(4) returns(expand.grid(1:3, 1:3, 1:3, 1:3))

etc.

like image 546
robbie Avatar asked Nov 18 '25 16:11

robbie


1 Answers

combinations <- function(n)
    expand.grid(rep(list(1:3),n))

> combinations(2)
  Var1 Var2
1    1    1
2    2    1
3    3    1
4    1    2
5    2    2
6    3    2
7    1    3
8    2    3
9    3    3
> combinations(3)
   Var1 Var2 Var3
1     1    1    1
2     2    1    1
3     3    1    1
4     1    2    1
5     2    2    1
6     3    2    1
7     1    3    1
8     2    3    1
9     3    3    1
10    1    1    2
11    2    1    2
12    3    1    2
13    1    2    2
14    2    2    2
15    3    2    2
16    1    3    2
17    2    3    2
18    3    3    2
19    1    1    3
20    2    1    3
21    3    1    3
22    1    2    3
23    2    2    3
24    3    2    3
25    1    3    3
26    2    3    3
27    3    3    3
like image 130
Thomas Avatar answered Nov 20 '25 07:11

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!