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.
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)).
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