向量与多个元素的共同元素 [英] Common elements of vectors with multiple elements
本文介绍了向量与多个元素的共同元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何有效地查找具有重复元素的两个向量的公共元素?
How to efficiently find common elements of two vectors with duplicate elements?
示例:
v1 <- c(1, 1, 2, 3, 3, 4)
v2 <- c(1, 1, 1, 3, 4, 5)
commonElements <- c(1, 1, 3, 4)
intersect
不能很好地处理重复元素.
intersect
doesn't handle duplicate elements well.
推荐答案
我喜欢intersect
和table
s,所以...
I like intersect
and table
s, 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
但是,如果您真的想要该矢量,则为:as.numeric(rep(names(comtab),comtab))
.
If you really want that vector, though, it's: as.numeric(rep(names(comtab),comtab))
.
这篇关于向量与多个元素的共同元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文