[R] comparing rows - a possible solution

Oliver Bandel oliver at first.in-berlin.de
Mon Nov 10 23:15:54 CET 2008


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



More information about the R-help mailing list