ECII
ECII

Reputation: 10629

Search within a string that does not contain a pattern

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?

Upvotes: 40

Views: 74911

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

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]

Upvotes: 74

Related Questions