“Set Difference” between two vectors with duplicate values

前端 未结 3 1623
孤城傲影
孤城傲影 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:13

    match with a little for-loop does work:

    > f(x, y)
    [1] 1 3 8
    > f(x, z)
    [1] 1 5 7
    

    Code

    f <- function(s, r) {
        for(i in 1:length(s)){
            j <- match(s[i], r)
            if(!is.na(j)) {
                s[i] <- NA
                r[j] <- NA
            } 
        }
        print(s[complete.cases(s)])
    }
    

提交回复
热议问题