I want to create a matrix in R with a set number of variables (e.g. 1 to 10). Those variables should be randomly assigned over rows and columns BUT should not be repeated in either (so number 1 should be once in row 1 and once in column 1)!
So for example:
1,2,3,4,5,6,7,8,9,10
2,3,4,5,6,7,8,9,10,1
3,4,5,6,7,8,9,10,1,2
4,5,6,7,8,9,10,1,2,3
5,6,7,8,9,10,1,2,3,4
6,7,8,9,10,1,2,3,4,5
7,8,9,10,1,2,3,4,5,6
8,9,10,1,2,3,4,5,6,7
9,10,1,2,3,4,5,6,7,8
10,1,2,3,4,5,6,7,8,9
But of course in that example the numbers are ascending and I want them randomized. I tried simple matrix demands but I cannot figure out how to do this. Can anyone help? Thanks in advance!
This seems almost like generating a
Sudoku
grid. The code below works pretty fast, but some minorR
optimizations could be done:Testing:
Unless I'm misunderstanding the problem, there's a much simpler way to create this shuffled matrix, without any loops or complicated conditional statements.