[R] comparing rows

markleeds at verizon.net markleeds at verizon.net
Mon Nov 10 18:15:51 CET 2008


hi chris: i'm betting  that there is a better/shorter more R'ish way to 
do it ( if someone could provide that, it's appreciated ) but below will 
get the output in the format you need. the all function tests whether 
all the elements are equal so you don't need setequal although i guess 
it's a matter of taste ?

as.vector((t(sapply(1:nrow(testmat1),function(.rowindex1) {
       sapply(1:nrow(testmat2), function(.rowindex2) {
          all(testmat2[.rowindex2,] == testmat1[.rowindex1,])
        })
     }))
))

 
#===========================================================================

Hello R-users,

I have a little problem.

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)

print(testmat1)
print(testmat2)

Both matrix differs in the last row.

Now I create a loop:

for (i in (1:4)){
for (j in (1:4)){
b <- (c(setequal(testmat1[j,],testmat2[i,])))
print(b)
}
}

R outputs me the following:

[1] TRUE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] TRUE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] TRUE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE

but I need one vector like this:

[1] TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE
FALSE FALSE FALSE FALSE


as.vector((t(sapply(1:nrow(testmat1),function(.rowindex1) {
       sapply(1:nrow(testmat2), function(.rowindex2) {
          all(testmat2[.rowindex2,] == testmat1[.rowindex1,])
        })
     }))
))



More information about the R-help mailing list