Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of overlapping elements

Tags:

r

vector

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.

like image 996
Anita Avatar asked Dec 19 '22 08:12

Anita


2 Answers

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)
like image 179
zx8754 Avatar answered Jan 07 '23 15:01

zx8754


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
like image 37
James Avatar answered Jan 07 '23 14:01

James