Count the number of identical elements in one position in two vectors

I have two vectors:

set.seed(12)

a<-sample(c(0,1),10,replace=T)

b<-sample(c(0,1),10,replace=T)

> a
 [1] 0 1 1 0 0 0 0 1 0 0
> b
 [1] 0 1 0 0 0 0 0 1 1 0

      

I would like to count the number of elements that match in two vectors.

So in the above case:

the following elements correspond: 1,2,4,5,6,7,8,10.

I cannot do this with set statements because I am not interested in common elements, but also their position.

+3


source to share


1 answer


Try to use which

and==

which(a==b)
#[1]  1  2  4  5  6  7  8 10

      



Using @David Arenburg example

 set.seed(12)
 a <- sample(c(0,1),10,replace=TRUE)
 b <- sample(c(0,1),10,replace=TRUE)
 c <- sample(c(0,1),10,replace=TRUE) # added

 which(rowSums(cbind(a,b,c)==a)==3)
#[1] 1 2 5 6

      

+4


source







All Articles