Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grepl: Search within a string that does not contain a pattern

Tags:

r

grepl

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?

like image 712
ECII Avatar asked Jan 17 '12 16:01

ECII


People also ask

What is the difference between grep and Grepl?

Both functions allow you to see whether a certain pattern exists in a character string, but they return different results: grepl() returns TRUE when a pattern exists in a character string. grep() returns a vector of indices of the character strings that contain the pattern.

What does the grep() function do?

The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.

What is grep() in R?

The grep() function in R is used to check for matches of characters or sequences of characters in a given string.

Is Grepl a base R?

The grepl in R is a built-in function that searches for matches of a string or string vector. The grepl() method takes a pattern and returns TRUE if a string contains the pattern, otherwise FALSE.


1 Answers

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]
like image 98
Joshua Ulrich Avatar answered Oct 29 '22 18:10

Joshua Ulrich