我有一个字符向量,我想从中排除第二个向量中存在的元素。我仍然不知道在这种情况下如何处理否定,同时还要考虑整个向量
vector[vector ! %in% vector2]
我显然可以vector[vector != single_character]
,但这只适用于单个角色。
答案 0 :(得分:9)
你很亲密
vector[!vector %in% vector2]
或者,即使你说“不使用setdiff”
setdiff(vector, vector2)
答案 1 :(得分: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"
答案 2 :(得分:1)
您可以定义新的运算符
`%ni%` = Negate(`%in%`)
答案 3 :(得分: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"