0
x <- c("a", "b", "c", "d", "e", "f", "g")
y <- c("a", "c", "d", "z")

I am trying to compare y to x and find an index where in y that does not match with anything in x. in this case z does match and I want R to return the index of z.

This is one of the things I tried and it does not work.

index <- which(y != x)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • If you just need the values rather than the indexes, use https://stackoverflow.com/questions/1837968/how-to-tell-what-is-in-one-vector-and-not-another – MrFlick Feb 19 '20 at 03:23

2 Answers2

3

use the operator %in%

 which(!y%in%x)
Filippo
  • 309
  • 1
  • 2
  • 10
1

You can also use match which will return NA if there is no match.

which(is.na(match(y, x)))
#[1] 4

Or another variation with setdiff

which(y %in% setdiff(y, x))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213