upabove
upabove

Reputation: 1119

Count number of same elements in the same 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 which match in the two vectors.

So in the above case:

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

I cannot do this with set operators because I'm not interested in the common elements, but also in their position.

Upvotes: 4

Views: 3370

Answers (1)

akrun
akrun

Reputation: 886938

Try using which and ==

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

Using @David Arenburg's 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

Upvotes: 5

Related Questions