A subset on all but empty grep returns an empty vector

Suppose I have a character vector that I would like to multiply for elements that do not match some regular expression. I could use the operator - to remove the subset that matches grep :

 > vec <- letters[1:5] > vec [1] "a" "b" "c" "d" "e" > vec[-grep("d", vec)] [1] "a" "b" "c" "e" 

Everything is returned to me, except for records that match "d" . But if I look for a regex that is not found, instead of putting everything back, as expected, I get nothing:

 > vec[-grep("z", vec)] character(0) 

Why is this happening?

+6
source share
1 answer

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" 
+9
source

Source: https://habr.com/ru/post/952404/


All Articles