Luis Alberts
Luis Alberts

Reputation: 43

Subseting a matrix based in a TRUE/FALSE matrix in R?

I have matrix of true and false value named originaldata. And a second matrix with X measurement called finalmatrix. To conserve in the final matrix only the values that are TRUE in originaldata and set to 0 the rest, I'm doing the following loop

 for (row in 1:sqrt(length(finalmatrix)))
 {
     for (col in 1:sqrt(length(finalmatrix))) 
     {
      if (originaldata[row,col] == FALSE) {
        finalmatrix[row,col] <- 0
      }
   }
 }

But this is painfully slow, specially with big matrices. Is there a more straightforwad way to do this?

Upvotes: 1

Views: 733

Answers (2)

smu
smu

Reputation: 9057

You could multiply the two matrixes and all values with FALSE in originaldata would become zero.

finalmatrix <- finalmatrix * originaldata

Upvotes: 2

cdeterman
cdeterman

Reputation: 19960

You can just set all the false elements to zero directly.

finalmatrix[!originaldata] = 0

Upvotes: 1

Related Questions