Home > Blockchain >  Compare two matrices, keeping values in one matrix that are TRUE in the other
Compare two matrices, keeping values in one matrix that are TRUE in the other

Time:05-06

This seems to be an easy task, which I am not finding a solution on R after looking up here and elsewhere. I have two matrices, one with string values and another with logical values.

a <- matrix(c(
              "A", "B", "C"
              ))

b <- matrix(c(
              T, F, T
              ))
> b
      [,1]
[1,]  TRUE
[2,] FALSE
[3,]  TRUE
> a
     [,1]
[1,] "A"
[2,] "B"
[3,] "C"

I need to create a third matrix that keeps values in the first that are TRUE in the second, and leaving NA on the remainder, like so:

> C
      [,1]
[1,]  "A"
[2,]  NA
[3,]  "C"

  • How do I achieve the above result?

CodePudding user response:

C <- matrix(a[ifelse(b, T, NA)], ncol = ncol(a))

CodePudding user response:

Here is an alternative by just assigning the NA to FALSE:

a[b==FALSE] <- NA
     [,1]
[1,] "A" 
[2,] NA  
[3,] "C"

CodePudding user response:

using which:

c<-a
c[which(b==FALSE)]<-NA

CodePudding user response:

a <- a[b] . This might also work, Depending on how you want the result.

  • Related