[R] comparing rows - a possible solution

From: Oliver Bandel <oliver_at_first.in-berlin.de>
Date: Mon, 10 Nov 2008 23:15:54 +0100


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. Received on Mon 10 Nov 2008 - 22:18:46 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 11 Nov 2008 - 01:30:24 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive