How to get a matrix with all combinations of three values in R?

Suppose we have a vector x with three values:

x <- c(0,1,2)

How to fill a matrix with 5 columns (V1, V2, V3, V4, V5) with combinations of all those values.

For example, we'd have:

V1 V2 V3 V4 V5
0   0  0  0  0 
0   0  0  0  1
0   0  0  1  1
...
0   1  0  0  0
...
1   1  1  1  1
...
1   2  1  0  1
...

Is there a way to do that?

Upvotes: 1

Views: 415

Answers (1)

DatamineR
DatamineR

Reputation: 9618

Something like:

 head(expand.grid(x,x,x,x,x))
  Var1 Var2 Var3 Var4 Var5
1    0    0    0    0    0
2    1    0    0    0    0
3    2    0    0    0    0
4    0    1    0    0    0
5    1    1    0    0    0
6    2    1    0    0    0

Upvotes: 5

Related Questions