1

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

Wilson Souza
  • 830
  • 4
  • 12

2 Answers2

3

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"
Paul
  • 2,850
  • 1
  • 12
  • 37
0

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.

Patrick
  • 1,057
  • 9
  • 23