[R] How to subset a matrix?

Sarah Goslee sarah.goslee at gmail.com
Tue Jun 12 19:10:51 CEST 2012


Providing a reproducible example is a good idea, but what about this:

> A <- matrix(1:20, nrow=4)
> MASK <- matrix(FALSE, nrow=4, ncol=5)
> MASK[2:3, 1:3] <- TRUE
> MASK
      [,1]  [,2]  [,3]  [,4]  [,5]
[1,] FALSE FALSE FALSE FALSE FALSE
[2,]  TRUE  TRUE  TRUE FALSE FALSE
[3,]  TRUE  TRUE  TRUE FALSE FALSE
[4,] FALSE FALSE FALSE FALSE FALSE
> A[rowSums(MASK) > 0, colSums(MASK) > 0]
     [,1] [,2] [,3]
[1,]    2    6   10
[2,]    3    7   11

Alternatively, you could take the vector returned by:
> A[MASK]
[1]  2  3  6  7 10 11

and put it back into matrix format.

Sarah

On Tue, Jun 12, 2012 at 12:44 PM, Michael <comtech.usa at gmail.com> wrote:
> Hi all,
>
> Lets say I have a matrix A which is m x n.
>
> I also have a mask matrix MASK which is m x n with values in T/F, where T
> values make a sub-matrix in regutangular shape...
>
> I applied B=A[MASK] and it didn't work as expected...
>
> Any thoughts?


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list