Which numbers are present in a vector but not in another one [duplicate]

╄→гoц情女王★ 提交于 2019-12-01 14:37:25
setdiff(v1, v2)
# [1]  1  3  5  6  8  9 10

Use the %in% operator with logical NOT ( ! ) to subset v1 by values not in v2:

v1[ ! v1 %in% v2 ]
#[1]  1  3  5  6  8  9 10

Or you could look for non-matches of v1 in v2 (this is almost the same):

v1[ is.na( match( v1 , v2 ) ) ]
#[1]  1  3  5  6  8  9 10

Or using which to get the indices:

v1[  which( ! v1 %in% v2 ) ]
#[1]  1  3  5  6  8  9 10

All flavours of the same thing. And there are many more ways to do this. Definitely don't use a loop for this because this kind of operation is a perfect example of how you can take advatage of R's vectorisation. Loops are better to be called for their side-effects and/or when the processing to number of iterations ratio is large.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!