This is because grep returns an integer vector, and when there is no match, it returns integer(0) .
> grep("d", vec) [1] 4 > grep("z", vec) integer(0)
and since the - operator works elementarily, and integer(0) has no elements, negation does not change the integer vector:
> -integer(0) integer(0)
therefore, vec[-grep("z", vec)] evaluates to vec[-integer(0)] , which in turn evaluates to vec[integer(0)] , which is equal to character(0) .
You will get the expected behavior with invert = TRUE :
> vec[grep("d", vec, invert = TRUE)] [1] "a" "b" "c" "e" > vec[grep("z", vec, invert = TRUE)] [1] "a" "b" "c" "d" "e"
source share