9

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?

Henrik
  • 65,555
  • 14
  • 143
  • 159
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 1
    I took the intent to assign NA from the specified result and from the fact that both his solution and my alternate gave the same result. – IRTFM Jan 05 '16 at 17:29

2 Answers2

9

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.)

IRTFM
  • 258,963
  • 21
  • 364
  • 487
0

Both solutions provide above works and are fine. Here is another solution to produce a new matrix, without modifying the previous one. Make sure that your matrix of logical values are well store as logical, and not as character.

vm <- as.vector(m)
vi <- as.vector(i)
new_v <- ifelse(vi, vm, NA)
new_mat <- matrix(new_v, nrow = nrow(m), ncol=ncol(m))
VincentP
  • 89
  • 10
  • I'm guessing that it would have been simpler and faster to simply create a copy that could then be modified. The `ifelse` would have needed to create 3 object of the same length as the original matrix and then do an assignment into a fourth one. – IRTFM Nov 24 '20 at 19:49
  • Yes of course. There is always different ways to do. I just wanted to give another example of how solve this problem, step by step. (which is sometimes easier to understand for beginners). – VincentP Nov 26 '20 at 11:01