generate a matrix of all possible combinations of 5 numbers in n columns

Hello,

I would like to create a matrix for n columns. That matrix then has rows with all the possible combinations using the numbers 0, 1, 2, 3, 4

For example, when n is 3, you get columns A, B and C (column names for example) and then a matrix is produced as below. That would be a matrix of 125 rows (in the example below it has a break to shorten the example).

The total number of rows gets multiplied by 5, for each extra column.

Anybody knows how to write a code that can create this matrix using only n as the variable factor?

thanks!

A B C
0 0 0
1 0 0
2 0 0
3 0 0
4 0 0
0 1 0
1 1 0
2 1 0
3 1 0
4 1 0
0 2 0
1 2 0
2 2 0
3 2 0
4 2 0
0 3 0
1 3 0
2 3 0
3 3 0
4 3 0
0 4 0
1 4 0
2 4 0
3 4 0
4 4 0
0 0 1
1 0 1
2 0 1
3 0 1
4 0 1
0 1 1
1 1 1
2 1 1
3 1 1
4 1 1
0 2 1
1 2 1
2 2 1
3 2 1
4 2 1
0 3 1
1 3 1
2 3 1
3 3 1
4 3 1
0 4 1
1 4 1
2 4 1
3 4 1
4 4 1
0 0 4
1 0 4
2 0 4
3 0 4
4 0 4
0 1 4
1 1 4
2 1 4
3 1 4
4 1 4
0 2 4
1 2 4
2 2 4
3 2 4
4 2 4
0 3 4
1 3 4
2 3 4
3 3 4
4 3 4
0 4 4
1 4 4
2 4 4
3 4 4
4 4 4

There may be a more elegant solution:

n <- 5
expand.grid(rep(list(seq(0, n - 1)), 3))

thank you, this works!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.