“Set Difference” between two vectors with duplicate values

前端 未结 3 1619
孤城傲影
孤城傲影 2020-12-06 20:37

I have 3 vectors

x <- c(1,3,5,7,3,8)
y <- c(3,5,7)
z <- c(3,3,8)

I want to find the elements of x that are not in

3条回答
  •  無奈伤痛
    2020-12-06 21:10

    Here's an attempt using make.unique to account for duplicates:

    dupdiff <- function(x,y) x[-match(
      make.unique(as.character(y)),
      make.unique(as.character(x)),
      nomatch=0
    )]
    

    Testing:

    dupdiff(x,y)
    #[1] 1 3 8
    dupdiff(x,z)
    #[1] 1 5 7
    dupdiff(x, c(5, 7))
    #[1] 1 3 3 8
    dupdiff(x, c(5, 7, 9))
    #[1] 1 3 3 8
    

提交回复
热议问题