4

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 considering the entire vector

vector[vector ! %in% vector2]

I can obviously do vector[vector != single_character] but that only works for a single character.

4

4 回答 4

11

你很近

vector[!vector %in% vector2]

或者,即使您说“不使用 setdiff”

setdiff(vector, vector2)
于 2012-09-27T18:51:36.877 回答
1

您可以定义一个新的运算符,

 `%ni%` = Negate(`%in%`)
于 2012-09-27T21:14:18.877 回答
1
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"
于 2012-09-27T18:51:46.230 回答
0

现在有一个更优雅的解决方案:

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"
于 2019-10-11T12:37:49.580 回答