简体   繁体   中英

R: Comparing two binary vectors

Im new to R. I have two vectors of zeros and ones. I want to find which rows are both zeros, both ones. zeros to one or one to zeros. I cannot seem to find a question considering this. Thanks

ex.

  a=c(0,0,0,1,0,1,1,1,0,1)
  b=c(1,0,1,0,0,0,0,1,1,1)

You are looking for table ...

table( a , b )
   b
a   0 1
  0 2 3
  1 3 2

to make a distinction between cases , you can use & operator, so, to find a case when a==X and b==Y:

which( (a==X) & (b==Y) )

eg.

which( (a==0) & (b==0) )

prints out

[1] 2 5

while

which( (a==1) & (b==0) )

prints

[1] 4 6 7

etc.

If the problem does not concern symmetries (we just want to find indices with the same/different values), one can use simple comparisions and which :

This is exactly what == is for

a==b
[1] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

and if you need indices, there is a which function

which( a==b )
[1]  2  5  8 10

for 0->1 or 1->0 case we can use != operator

which( a!=b )
[1] 1 3 4 6 7 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM