Anita
Anita

Reputation: 789

Number of overlapping elements

I've got two vectors:

vec1 <- c(1,0,1,1,1)
vec2 <- c(1,1,0,1,1)

The vectors have the same elements at position 1, 4 and 5.

How can I return the number of elements that overlap in 2 vectors taking the position into account? So, here I would like to return the number 3.

Upvotes: 4

Views: 223

Answers (2)

zx8754
zx8754

Reputation: 56159

Test for equality, then sum, you might want to exclude NAs:

sum(vec1==vec2, na.rm=TRUE)

EDIT Exclude 0==0 matches, by adding an exclusion like:

sum(vec1==vec2 & vec1!=0, na.rm=TRUE)

Thanks to @CarlWitthoft

Or, if you have only ones and zeros, then:

sum((vec1+vec2)==2, na.rm=TRUE)

Upvotes: 8

James
James

Reputation: 66834

If your entries are only 0 and 1 (or if you are only interested in 0 and anything that is not 0) you can use xor to determine where they differ and then sum its negation, otherwise you would have to test for equality as @zx8754 commented:

sum(!xor(vec1,vec2))
[1] 3

Upvotes: 3

Related Questions