Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 565
Doug Avatar asked Dec 12 '22 22:12

Doug


2 Answers

You're close

vector[!vector %in% vector2]

or, even though you said "not using setdiff"

setdiff(vector, vector2)
like image 124
GSee Avatar answered Dec 14 '22 11:12

GSee


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"
like image 23
Jilber Urbina Avatar answered Dec 14 '22 10:12

Jilber Urbina