[R] regex -> negate a word

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Sun Jan 18 20:22:51 CET 2009


Rau, Roland wrote:
> Dear all,
>
> let's assume I have a vector of character strings:
>
> x <- c("abcdef", "defabc", "qwerty")
>
> What I would like to find is the following: all elements where the word
> 'abc' does not appear (i.e. 3 in this case of 'x').
>   

a quick shot is:

x[-grep("abc", x)]

which unfortunately fails if none of the strings in x matches the
pattern, i.e., grep returns integer(0); arguably, x[integer(0)] should
rather return all elements of x:

"An empty index selects all values" (from ?'[')

but apparently integer(0) does not count as an empty index (and neither
does NULL).  so you may want something like:

strings = c("abcdef", "defabc", "qwerty")
pattern = "abc"
if (length(matching <- grep(pattern, strings))) x[-matching] else x

vQ




More information about the R-help mailing list