[R] comparing rows - a possible solution

markleeds at verizon.net markleeds at verizon.net
Tue Nov 11 01:17:20 CET 2008


Hi Oliver: if I understood Chris's email correctly , he wanted to 
compare all possible row ( row1 with the other 4 rows of the other 
matrix,
row 2 with the 4 rows of the other matrix, etc, etc, ) combinations of 
the two matrices, not the individual elements of the matrix. That's just 
my interpretation ?
If he did want to compare elements, then I agree with your solution, 
as.vector(testmat1 == testmat2).



On Mon, Nov 10, 2008 at  5:15 PM, Oliver Bandel wrote:

> Hello,
>
> sorry for posting this independently of the original thread, but it is
> not that easy to answer to mails, when receiving the r-help as
> digest...
>
> ...
>
>
> The question was:
>
>> I compare each row of a matrix with each row of another matrix.
>>
>> testmat1 <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16), nrow=4)
>> testmat2 <- matrix(c(1,2,3,5,5,6,7,8,9,10,11,12,13,14,15,16), nrow=4)
>
> and it was asked for a compaison of the both matrix-objects and the
> result should be a vetor with boolean results.
>
> I would use this one:
>
>    as.vector( testmat1 == testmat2 )
>
> or maybe
>
>   as.vector( t(testmat1) == t(testmat2) )
>
> but the result as a matrix might also be interesting,
> so as.vector() could be thrown out, and one would get
> a matrix of results.
>
> If you want just to know if a complete row is matching or not,
> you could sum up the rows:
>
> rowSums(testmat1 == testmat2 )
>
> and when you compare it with the length,
> you get a column-based match-boolean:
>
>
>   rowSums(testmat1 == testmat2 ) == nrow(testmat1)
>
> or if you need the negation of it:
>
>   !rowSums(testmat1 == testmat2 ) == nrow(testmat1)
>
> and as functions:
>
>   matcolcomp <-function(m1,m2) { rowSums(m1 == m2) == nrow(m1) }
>
> or
>
>   matcolcomp <-function(m1,m2) { ! ( rowSums(m1 == m2) == nrow(m1) ) }
>
>
> Ciao,
>    Oliver
>
> ______________________________________________
> 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