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.
Test for equality, then sum
, you might want to exclude NA
s:
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With