Shuffle 20% of values between two matrices in R

Viewed 37

I have two matrices, high dimensional. The number of columns in the matrices are same, however the rows are different. I want to shuffle 10%( or a fixed number say 50 samples) of samples between the matrices for 10 different times( random sampling). For each shuffle i want a new matrix with 10% samples shuffled between matrix A and matrix B.

A short example would be:

Matrix A:

sample A sample B sample C
8 1 8
4 2 4
6 9 9

Matrix B:

Sample 1 Sample 2 Sample 3 sample 4
8 1 5 6
5 1 1 7
9 5 8 2

Resultant Matrix(shuffle 1) Matrix A shuffled::

sample A sample B sample 2
8 1 1
4 2 1
6 9 5

Matrix B shuffled:

Sample 1 Sample B Sample 3 sample 4
8 8 5 6
5 4 1 7
9 9 8 2

I need these two matrices and then another 9 with shuffled randomly by 10%.

I would appreciate any help!

1 Answers

There might be a few issues with what you are trying to get done, as checking whether the matrices are shuffled correctly will be hard to do when there are duplicates in the matrix. That said, this is a possible solution:

set.seed(101)
mymat <- matrix(sample(1:9, size = 9, replace = T), 3, 3)
mymat
#>      [,1] [,2] [,3]
#> [1,]    9    1    3
#> [2,]    9    6    9
#> [3,]    7    3    3

myvector <- c(mymat)
ref_vec <- myvector
shuff <- sample(1:length(myvector), size = 0.4*length(myvector))
shuff <- rep_len(shuff, length(shuff)+1)

for(i in 1:(length(shuff)-1)){
  myvector[shuff[i]] = ref_vec[shuff[i+1]]
}

mymat <- matrix(myvector, 3, 3)
mymat
#>      [,1] [,2] [,3]
#> [1,]    9    7    3
#> [2,]    1    6    9
#> [3,]    9    3    3

You would have to tweak it considerably for your use case and implement it as a function.

This was a "40% shuffle" in the sense that only 40% of the elements changed position with each other.

It is more obvious when there are only unique elements in the matrix:

set.seed(101)
mymat <- matrix(sample(1:9, size = 9), 3, 3)
mymat
#>      [,1] [,2] [,3]
#> [1,]    9    8    7
#> [2,]    1    2    5
#> [3,]    6    3    4

myvector <- c(mymat)
ref_vec <- myvector
shuff <- sample(1:length(myvector), size = 0.4*length(myvector))
shuff <- rep_len(shuff, length(shuff)+1)

for(i in 1:(length(shuff)-1)){
  myvector[shuff[i]] = ref_vec[shuff[i+1]]
}

mymat <- matrix(myvector, 3, 3)
mymat
#>      [,1] [,2] [,3]
#> [1,]    9    8    7
#> [2,]    1    2    3
#> [3,]    5    6    4
Related