1

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
jenswirf
  • 6,607
  • 9
  • 44
  • 64

2 Answers2

5

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
...
Roman Luštrik
  • 67,056
  • 24
  • 151
  • 191
mnel
  • 110,110
  • 27
  • 254
  • 248
1

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
...
krlmlr
  • 23,618
  • 14
  • 112
  • 204