I'll demonstrate the solution on 3 by 3 datasets. First thing I would do is convert the data.frame to matrix to be able to easily apply permutations.
Let's say we have a 3x3 matrix:
set.seed(1)
m <- matrix(sample(1:100, 9), nrow = 3)
m
#> [,1] [,2] [,3]
#> [1,] 68 34 14
#> [2,] 39 87 82
#> [3,] 1 43 59
Then each shuffle can be defined by a permutation of numbers 1 to 9.
shuffle <- c(9, 4, 7, 1, 8, 3, 2, 5, 6)
matrix(m[shuffle], nrow = 3)
#> [,1] [,2] [,3]
#> [1,] 59 68 39
#> [2,] 34 82 87
#> [3,] 14 1 43
So our task then is to generate 9 such permutations where each number occurs on each position exatly once. E.g. having first shuffle c(9, 4, 7, 1, 8, 3, 2, 5, 6)
, we can't have c(9, 2, 7, 3, 8, 5, 4, 6, 1)
then because 9 has already been on the first place, 7 on the third and 8 on the fifth.
Basically what we need is a 9 by 9 latin square. Fortunately, there is a package for such things:
library(magic)
#> Loading required package: abind
set.seed(1)
shuffles_matrix <- rlatin(9)
shuffles_matrix
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#> [1,] 6 5 4 2 3 9 8 1 7
#> [2,] 4 2 7 6 9 8 1 3 5
#> [3,] 8 3 1 5 2 7 9 4 6
#> [4,] 5 1 9 7 6 2 4 8 3
#> [5,] 3 6 5 1 8 4 7 9 2
#> [6,] 9 7 8 3 1 6 5 2 4
#> [7,] 7 9 3 4 5 1 2 6 8
#> [8,] 2 8 6 9 4 5 3 7 1
#> [9,] 1 4 2 8 7 3 6 5 9
Now we can treat each row of this square as a shuffle of our original 3x3 matrix:
shuffles <- split(shuffles_matrix, 1:9)
shuffles
#> $`1`
#> [1] 6 5 4 2 3 9 8 1 7
#>
#> $`2`
#> [1] 4 2 7 6 9 8 1 3 5
#>
#> $`3`
#> [1] 8 3 1 5 2 7 9 4 6
#>
#> $`4`
#> [1] 5 1 9 7 6 2 4 8 3
#>
#> $`5`
#> [1] 3 6 5 1 8 4 7 9 2
#>
#> $`6`
#> [1] 9 7 8 3 1 6 5 2 4
#>
#> $`7`
#> [1] 7 9 3 4 5 1 2 6 8
#>
#> $`8`
#> [1] 2 8 6 9 4 5 3 7 1
#>
#> $`9`
#> [1] 1 4 2 8 7 3 6 5 9
And this is how we apply these shuffles to the matrix:
library(purrr)
shuffles %>%
map(~matrix(m[.], nrow = 3))
#> $`1`
#> [,1] [,2] [,3]
#> [1,] 43 39 82
#> [2,] 87 1 68
#> [3,] 34 59 14
#>
#> $`2`
#> [,1] [,2] [,3]
#> [1,] 34 43 68
#> [2,] 39 59 1
#> [3,] 14 82 87
#>
#> $`3`
#> [,1] [,2] [,3]
#> [1,] 82 87 59
#> [2,] 1 39 34
#> [3,] 68 14 43
#>
#> $`4`
#> [,1] [,2] [,3]
#> [1,] 87 14 34
#> [2,] 68 43 82
#> [3,] 59 39 1
#>
#> $`5`
#> [,1] [,2] [,3]
#> [1,] 1 68 14
#> [2,] 43 82 59
#> [3,] 87 34 39
#>
#> $`6`
#> [,1] [,2] [,3]
#> [1,] 59 1 87
#> [2,] 14 68 39
#> [3,] 82 43 34
#>
#> $`7`
#> [,1] [,2] [,3]
#> [1,] 14 34 39
#> [2,] 59 87 43
#> [3,] 1 68 82
#>
#> $`8`
#> [,1] [,2] [,3]
#> [1,] 39 59 1
#> [2,] 82 34 14
#> [3,] 43 87 68
#>
#> $`9`
#> [,1] [,2] [,3]
#> [1,] 68 82 43
#> [2,] 34 14 87
#> [3,] 39 1 59