Home > database >  Compare 2 matrices and fill a matrix with 1 or 0 based on group condition
Compare 2 matrices and fill a matrix with 1 or 0 based on group condition

Time:05-27

I was wondering if there is a way to avoid using nested ifs inside a loop to this problem:

  • I have a 100 x 14 matrix with values. Column 1 is the group to which each row belongs (there are a total of 11 groups). Let's call it MatrixA.
  • Matrix B, has the average value for each column for each of the 11 different groups (size 11x14, where the first column has the group number).
  • I have columns in the same order for both Matrices

I want to change the values of MatrixA to 1 if the value on the cell is greater than the average value from Matrix B, otherwise, put 0. If cell[1,2] in MatrixA belongs to group 5, then check the mean of group 5 column 2 in MatrixB and put 1 or 0, and so on.

MatrixA = cbind(sample(1:11,100,replace = T),matrix(data = rnorm(100*13),nrow = 100,ncol = 13 ))

Let's assume these are the averages of each column from MatrixA MatrixB = cbind(1:11,matrix(data = rnorm(11*13),nrow = 11,ncol = 13 ))

I hope phrase my question correctly. Thank you.

CodePudding user response:

Try

(MatrixA>MatrixB[match(MatrixA[,1],MatrixB[,1]),])*1L

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    1    1    1
[2,]    0    1    1    0    1
[3,]    0    1    1    1    1
[4,]    0    1    1    0    1
[5,]    0    1    1    1    0
...

note: the first column (groups) will be all 0's, you can replace it back again to get the groups.

  • Related