Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common elements of vectors with multiple elements

How to efficiently find common elements of two vectors with duplicate elements?

Example:

v1 <- c(1, 1, 2, 3, 3, 4)  
v2 <- c(1, 1, 1, 3, 4, 5)  
commonElements <- c(1, 1, 3, 4)

intersect doesn't handle duplicate elements well.

like image 245
Tomek Tarczynski Avatar asked Dec 17 '25 19:12

Tomek Tarczynski


1 Answers

I like intersect and tables, so...

tv1 <- table(v1)
tv2 <- table(v2)
comvals <- intersect(names(tv1),names(tv2))
comtab <- apply(rbind(tv1[comvals],tv2[comvals]),2,min)

The information is still there, but in (what I view as) a nicer format:

> comtab
1 3 4 
2 1 1 

EDIT: If you really want that vector, though, it's: as.numeric(rep(names(comtab),comtab)).

like image 80
Frank Avatar answered Dec 20 '25 12:12

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!