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?
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.
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.
The grep() function in R is used to check for matches of characters or sequences of characters in a given string.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With