Get elements in a vector that are not present in other vectors

Viewed 34

I have the following 3 vectors:

vec <- c("a", "b", "c", "d", "e", "f", "g", "h")
vec1 <- c("a", "d", "f", "h")
vec2 <- c("b", "c")

I would to get a new vector that contain the elements present in vec, that are not present in vec1 and vec2

output desired:

output <- c("e", "g")

Thanks all

2 Answers

You could use setdiff() and use c() to concatenate vec1 and vec2.

vec <- c("a", "b", "c", "d", "e", "f", "g", "h")
vec1 <- c("a", "d", "f", "h")
vec2 <- c("b", "c")
setdiff(vec, c(vec1, vec2))

Output:

> setdiff(vec, c(vec1, vec2))
[1] "e" "g"

vec[which(!vec %in% c(vec1, vec2))]

vec %in% c(vec1, vec2) returns TRUE for elements of vec that are in vec1 and vec2 combined and FALSE otherwise. !vec %in% c(vec1, vec2) does the opposite, i.e., it returns TRUE for elements of vec that are not in vec1 or vec2. which returnes the position index for those returned TRUE, which can be used by vec[] to extract the original elements from vec.

Related