Excluding elements of a vector from another vector, not using setdiff

后端 未结 4 1146
面向向阳花
面向向阳花 2021-01-19 06:30

I have a character vector, and I want to exclude elements from it which are present in a second vector. I don\'t know how to work the negation in this case while still consi

相关标签:
4条回答
  • 2021-01-19 07:08

    A more elegant solution is available now:

    library(textclean)
    # master character vector
    vector1 = c("blue", "green", "red")
    # vector containing elements to be removed from master vector
    vector2 = c("green", "red")
    drop_element_fixed(vector1, vector2)
    
    # Output:
    # [1] "blue"
    
    0 讨论(0)
  • 2021-01-19 07:11
    vector1 <- letters[1:4]
    set.seed(001)
    vector2 <- sample(letters[1:15], 10, replace=TRUE)
    
     vector1
    [1] "a" "b" "c" "d"
    vector2
     [1] "d" "f" "i" "n" "d" "n" "o" "j" "j" "a"
    
    vector2 [!(vector2 %in% vector1)] # elements in vector2 that are not in vector1
    [1] "f" "i" "n" "n" "o" "j" "j"
    
    0 讨论(0)
  • 2021-01-19 07:27

    You're close

    vector[!vector %in% vector2]
    

    or, even though you said "not using setdiff"

    setdiff(vector, vector2)
    
    0 讨论(0)
  • 2021-01-19 07:27

    You can define a new operator,

     `%ni%` = Negate(`%in%`)
    
    0 讨论(0)
提交回复
热议问题