Difference between two vectors in R

那年仲夏 提交于 2020-06-07 13:42:09

问题


I have two vectors:

a <- c(1, 1, 3, 4, 5, 7, 9)
b <- c(2, 3, 4, 6, 8, 2)

I want to find the numbers in the second vector, which are not in the first vector:

dif <- c(2, 6, 8)

I've tried many different approaches (such as merge, different types of joins (dplyr package), setdiff, compare (compare package)), but I still can't find a way to do it.


回答1:


You can use setdiff

setdiff(b,a)
#[1] 2 6 8



回答2:


An alternative way, instead of setdiff (which is probably preferrable), is to use %in%

unique(b[! b %in% a])
#[1] 2 6 8


来源:https://stackoverflow.com/questions/31573087/difference-between-two-vectors-in-r

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