[R] How to subset a matrix?

David Winsemius dwinsemius at comcast.net
Tue Jun 12 20:20:59 CEST 2012


On Jun 12, 2012, at 1:58 PM, David Winsemius wrote:

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

I see I failed to transpose the line that created wM

wM <- which(MASK, arr.ind=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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list