soyannaR
soyannaR

Reputation: 1

Indexing using a boolean matrix in R

I'm stumped using indexing in R. I have two matrices, one with logical values and one with data. I want to use the first to index into the second one. However, I've noticed that R reorders my values when doing so.

My data looks roughly like this:

ind <- matrix(c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE), nrow = 3, ncol = 4, byrow = TRUE)

data <- matrix(c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4), nrow = 3, ncol = 4, byrow = TRUE)

Now, when indexing result <- data[ind], I was obtaining the following: c(1, 3, 4) when I was trying to obtain c(1, 4, 3).

How can I prevent R from reordering columwise? I'd appreciate any input. I'm sure it's an easy fix - I just don't know which.

Thank you!

Upvotes: 0

Views: 1206

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

Here is another base R trick (but I recommend the answer by @c0bra)

> rowSums(data * ind)
[1] 1 4 3

Upvotes: 0

c0bra
c0bra

Reputation: 1080

When converting matrices to and from vectors, R makes the transformation columnwise.

as.vector(data) 
 [1] 1 1 1 2 2 2 3 3 3 4 4 4

As this happens to both your ind and your data this is generally not a problem.

So to retain your order, you have to transpose both matrices:

> t(data)[t(ind)]
[1] 1 4 3

PS: have you tried which with a matrix?

> which(arr.ind = T, ind)
     row col
[1,]   1   1
[2,]   3   3
[3,]   2   4

Upvotes: 1

Related Questions