r - Subsetting on all but empty grep returns empty vector -


suppose have character vector, i'd subset elements don't match regular expression. might use - operator remove subset grep matches:

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

i'm given except entries matched "d". if search regular expression isn't found, instead of getting expect, nothing back:

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

why happen?

it's because grep returns integer vector, , when there's no match, returns integer(0).

> grep("d", vec) [1] 4 > grep("z", vec) integer(0) 

and since - operator works elementwise, , integer(0) has no elements, negation doesn't change integer vector:

> -integer(0) integer(0) 

so vec[-grep("z", vec)] evaluates vec[-integer(0)] in turn evaluates vec[integer(0)], character(0).

you behavior expect 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" 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -