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

Viewed 55

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?
4 Answers
C <- matrix(a[ifelse(b, T, NA)], ncol = ncol(a))

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

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

using which:

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

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

Related