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?
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With