Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting NA in a matrix using another logical matrix

Tags:

indexing

r

na

I just saw what seemed like a perfectly good question that was deleted and since like the original questioner I couldn't find a duplicate, I'm posting again.

Assume that I have a simple matrix ("m"), which I want to index with another logical matrix ("i"), keeping the original matrix structure intact. Something like this:

# original matrix
m <- matrix(1:12, nrow = 3, ncol = 4)

# logical matrix
i <- matrix(c(rep(FALSE, 6), rep(TRUE, 6)), nrow = 3, ncol = 4)

m
i

# Desired output:
matrix(c(rep(NA,6), m[i]), nrow(m), ncol(m))
# however this seems bad programming...

Using m[i] returns a vector and not a matrix. What is the correct way to achieve this?

like image 232
IRTFM Avatar asked Jan 05 '16 17:01

IRTFM


1 Answers

The original poster added a comment saying he'd figured out a solution, then almost immediately deleted it:

 m[ !i ] <- NA 

I had started an answer that offered a slightly different solution using the is.na<- function:

 is.na(m) <- !i

Both solutions seem to be reasonable R code that rely upon logical indexing. (The i matrix structure is not actually relied upon. A vector of the proper length and entries would also have preserved the matrix structure of m.)

like image 162
IRTFM Avatar answered Nov 12 '22 05:11

IRTFM