Finding elements that do not overlap between two vectors

前端 未结 4 1760
一向
一向 2020-12-30 01:27

I\'m trying to identify elements which are not included in the other vector. For instance in two vectors I have

list.a <- c(\"James\", \"Mary\", \"Jack\",         


        
4条回答
  •  醉酒成梦
    2020-12-30 01:33

    An extended answer based on the comments from Hadley and myself: here's how to allow for duplicates.

    Final Edit: I do not recommend anyone use this, because the result may not be what you expect. If there is a repeated value in x which is not in y, you will see that value repeated in the output. But: if, say, there are four 9s in x and one 9 in y, all the 9s will be removed. One might expect to retain three of them; that takes messier code.

    mysetdiff<-function (x, y, multiple=FALSE) 
    {
        x <- as.vector(x)
        y <- as.vector(y)
        if (length(x) || length(y)) {
            if (!multiple) {
                 unique( x[match(x, y, 0L) == 0L])  
                  }else  x[match(x, y, 0L) == 0L] 
            } else x
    }
    
    Rgames> x
    [1]  8  9  6 10  9
    Rgames> y
    [1] 5 3 8 8 1
    Rgames> setdiff(x,y)
    [1]  9  6 10
    Rgames> mysetdiff(x,y)
    [1]  9  6 10
    Rgames> mysetdiff(x,y,mult=T)
    [1]  9  6 10  9
    Rgames> mysetdiff(y,x,mult=T)
    [1] 5 3 1
    Rgames> setdiff(y,x)
    [1] 5 3 1
    

提交回复
热议问题