Setting NA in a matrix using a different logical matrix

I just saw what seemed like a perfectly good question that was deleted, and since, like the original questionnaire, I could not find a duplicate, I send the message again.

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

# 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, not a matrix. What is the right way to achieve this?

+7
r indexing na
source share
1 answer

The original poster added a comment in which he decided that the solution, and then almost immediately deleted it:

  m[ !i ] <- NA 

I began to answer by suggesting a slightly different solution using the is.na<- function:

  is.na(m) <- !i 

Both solutions seem like reasonable R code that relies on logical indexing. (The matrix structure i is not really based. The vector of the correct length and records would also preserve the matrix structure m .)

+7
source share

All Articles