R Random Selection of Matrix Cells and Loop -


i have 2 3x3 matrices , randomly select item each row (the same corresponding item in both matrices) , record these 'selected' values in new matrix.

from there repeat process 5 times, each time adding matrix in end have 3x10 matrix of randomly selected values.

i try illustrate mean:

i have 2 matrices , b.

> = matrix( c(4,7,1,9,4,2,1,3,9), nrow = 3, ncol = 3) >      [,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 want randomly select integer between 1 , 3 (because there 3 columns in each of matrices)

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

since numbers 1,3 , 2, want create vector of 1st element of row 1, 3rd element of row 2 , 2nd element of row 3 both of matrices , b. 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, loop process 5 times, each time adding produced matrix on side of existing 'c" matrix.

i beginner in r question is: how incorporate random selection , loop create desired outcome? or advice appreciated, thanks.

(i recreate on larger scale)

you 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 

Comments