Reputation: 7317
I'm trying to generate all combinations of four variables, where each variable is an integral between 0 and 10. Is there an easy way to do this in R?
X | Y | Z | W
-------------
0 | 0 | 0 | 0
1 | 0 | 0 | 0
1 | 1 | 0 | 0
1 | 1 | 1 | 0
. . . .
. . . .
. . . .
10|10 |10 |10
Upvotes: 1
Views: 281
Reputation: 115390
If W
, X
, Y
and Z
exist
expand.grid(W = W, X = X, Y = Y, Z = Z)
W X Y Z
1 0 0 0 0
2 1 0 0 0
3 2 0 0 0
4 3 0 0 0
5 4 0 0 0
6 5 0 0 0
7 6 0 0 0
8 7 0 0 0
9 8 0 0 0
10 9 0 0 0
11 10 0 0 0
12 0 1 0 0
13 1 1 0 0
14 2 1 0 0
15 3 1 0 0
...
Upvotes: 5
Reputation: 25454
All combinations can be done with table
. Converting to a data frame yields to what you're looking for.
> as.data.frame(table(W=0:10, X=0:10, Y=0:10, Z=0:10))[, c('W','X','Y','Z')]
W X Y Z
1 0 0 0 0
2 1 0 0 0
3 2 0 0 0
4 3 0 0 0
5 4 0 0 0
6 5 0 0 0
7 6 0 0 0
8 7 0 0 0
9 8 0 0 0
10 9 0 0 0
11 10 0 0 0
12 0 1 0 0
13 1 1 0 0
...
Upvotes: 1