简体   繁体   中英

R Random Selection of Matrix Cells and Loop

I have two 3x3 matrices and I would like to randomly select an item from each row (the same corresponding item in both matrices) and record these 'selected' values in a new matrix.

From there I would like to repeat this process 5 times, each time adding to the matrix so that in the end I have a 3x10 matrix of randomly selected values.

I will try illustrate what I mean:

I have 2 matrices A and B.

> A = matrix( c(4,7,1,9,4,2,1,3,9), nrow = 3, ncol = 3)
> A
     [,1] [,2] [,3]
[1,]    4    9    1
[2,]    7    4    3
[3,]    1    2    9
> B = matrix( c(2, 4, 3, 1, 5, 7, 4, 3, 2), nrow=3, ncol=3) 
> B
     [,1] [,2] [,3] 
[1,]    2    1    4
[2,]    4    5    3
[3,]    3    7    2

I then want to randomly select an integer between 1 and 3 (because there are 3 columns in each of the matrices)

> random <- sample(1:3, length)
> random
[1] 1 3 2

since the numbers are 1,3 and 2, I want to create a vector of the 1st element of row 1, the 3rd element of row 2 and the 2nd element of row three from both of the matrices A and B. This would be the new matrix C.

> C = matrix(c(4,3,2,2,3,7), nrow = 3, ncol = 2)
> C
     [,1] [,2]
[1,]    4    2
[2,]    3    3
[3,]    2    7

After this, I would like to loop the process 5 times, each time adding the produced matrix on to the side of the existing 'C" matrix.

I am a beginner in R so my question is: How would I incorporate the random selection and the loop to create the desired outcome? Any help or advice is greatly appreciated, Thanks.

(I would like to recreate this on a much larger scale)

You could try

M <- cbind(c(t(A)), c(t(B)))
fnc <- function(){
  n <- nrow(A)
  ind <- sample(n) + (1:n-1)*n
  M[ind, ]
}
set.seed(0)
do.call(cbind, lapply(1:5, function(i)fnc()))
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    1    4    9    1    1    4    9    1    4     2
# [2,]    7    4    3    3    4    5    7    4    4     5
# [3,]    2    7    1    3    1    3    9    2    9     2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM