[R] How to subset a matrix?

David Winsemius dwinsemius at comcast.net
Tue Jun 12 19:58:01 CEST 2012


On Jun 12, 2012, at 12:44 PM, Michael 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...


Perhaps: (not fully tested in absence of reproducible example):

B=A[MASK]
MASK <- matrix(as.logical( c(0,0,0,0,0,
                        0,1,1,1,0,
                        0,1,1,1,0,
                        0,0,0,0,0,
                        0,0,0,0,0)), 5, byrow=TRUE)
#----

      row col
[1,]   2   2
[2,]   3   2
[3,]   2   3
[4,]   3   3
[5,]   2   4
[6,]   3   4
#-----
B <- matrix(B, nrow=1+diff(range(wM[,"row"])),
                ncol=1+diff(range(wM[,"col"])) )

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list