robbie
robbie

Reputation: 647

expand.grid with unknown set of variables

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.

Upvotes: 3

Views: 1954

Answers (1)

Thomas
Thomas

Reputation: 44525

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

Upvotes: 7

Related Questions