How can I get the complement of vector y in vector x

后端 未结 3 1167
臣服心动
臣服心动 2021-02-09 16:21

That\'s x \\ y using mathematical notation. Suppose

x <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,1,1,1,3) 
y <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,         


        
3条回答
  •  甜味超标
    2021-02-09 16:48

    How about this:

    R> x[x!=y]
    [1] 2 1 1 1 3
    Warning message:
    In x != y : longer object length is not a multiple of shorter object length
    R>
    

    This is difficult problem, I think, as you are mixing values and positions. The easier solution relies on one of the 'set' functions in R:

    R> setdiff(x,y)
    [1] 2 3
    

    but that uses only values and not position.

    The problem with the answer I gave you is the implicit use of recycling and the warning it triggered: as your x is longer than your y, the first few values of y get reused. But recycling is considered "clean" on when the longer vector has an integer-multiple length of the length of the shorter vector. But that is not the case here, and hence I am not sure we can solve your problem all that cleanly.

提交回复
热议问题