Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading