[R] Compare matrices

David Winsemius dwinsemius at comcast.net
Mon Jan 19 22:05:45 CET 2009


On Jan 19, 2009, at 3:54 PM, Dimitris Rizopoulos wrote:

> try this:
>
> A <- matrix(c(3,3,3,3,3,3,3,3,3),3,3)
> B <- matrix(c(T,T,T,F,T,T,F,T,F),3,3)
>
> C <- A
> C[!B] <- NA
> C
>

Very elegant. Another, perhaps less elegant, effort:

B[which(B == FALSE)] <- NA
 > B
      [,1] [,2] [,3]
[1,] TRUE   NA   NA
[2,] TRUE TRUE TRUE
[3,] TRUE TRUE   NA
 > C <- matrix(A * B, 3,3)   # A * B is *not* matrix multiplication
 >
 >
 > C
      [,1] [,2] [,3]
[1,]    3   NA   NA
[2,]    3    3    3
[3,]    3    3   NA

-- 
David Winsemius
>
> I hope it helps.
>
> Best,
> Dimitris
>
>
> Andrej Kastrin wrote:
>> Dear all,
>> Suppose that I have a matrix A
>>   A <- matrix(c(3,3,3,3,3,3,3,3,3),3,3)
>> and a logical matrix B
>>   B <- matrix(c(T,T,T,F,T,T,F,T,F),3,3)
>> The result  matrix should be
>>   C <- matrix(c(3,3,3,NA,3,3,NA,3,NA),3,3)
>> Is there any simple tip or trick to perform this without looping?
>> Thanks in advance for any suggestion.
>> Best regards, Andrej
>> ______________________________________________
>> 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.
>
> -- 
> Dimitris Rizopoulos
> Assistant Professor
> Department of Biostatistics
> Erasmus Medical Center
>
> Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
> Tel: +31/(0)10/7043478
> Fax: +31/(0)10/7043014
>
> ______________________________________________
> 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.




More information about the R-help mailing list