40

It appears that while grep has an invert argument, grepl does not.

I would like to subset for using 2 filters

data$ID[grepl("xyx", data$ID) & data$age>60]

How can I subset for age>60 and ID not containing "xyx"? What I did is

data$ID[abs(grepl("xyx", data.frame$ID)-1) & data$age>60]

which apparently works, but looks awful and unintuitive. Is there a nicer solution/argument?

zx8754
  • 52,746
  • 12
  • 114
  • 209
ECII
  • 10,297
  • 18
  • 80
  • 121

1 Answers1

73

grepl returns a logical vector. You can use the ! operator if you want the opposite result.

data$ID[!grepl("xyx", data$ID) & data$age>60]
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • You're welcome. Aren't you glad you just have to type `!` instead of `invert=TRUE`? ;-) – Joshua Ulrich Jan 17 '12 at 21:26
  • compared to the (abs()-1), the sole '!' looks so much nicer....Maybe one of you experts with the 20k+ reputations may find some time and write a nice review post about string operations in R. Just like joran did about the *apply family here http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega – ECII Jan 17 '12 at 21:31
  • Here's a try: http://biostat.mc.vanderbilt.edu/wiki/pub/Main/SvetlanaEdenRFiles/regExprTalk.pdf – AWE Nov 16 '12 at 11:35