[R] regex -> negate a word

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


Gabor Grothendieck wrote:
> Try this:
>
>
> # values
> setdiff(x, grep("abc", x, value = TRUE))
>
> Another possibility is:
>
> z <- "abc"
> x0 <- c(x, z) # to handle no match case
> x0[- grep(z, x0)] # values
>   

on quick testing, these two and the if-based version have comparable
runtime, with a minor win for the last one, and if the input is moderate
this makes no real difference.

however, the second solution above is likely to fail if the pattern is
more complex, e.g., contains a character class or a wildcard:

strings = c("xyz")
pattern = "a[a-z]"
strings[-grep(pattern, c(strings, pattern))]
# character(0)


vQ




More information about the R-help mailing list