I checked different posts on this, but still couldn't figure out why this is not working:
c=c("HI","NO","YESS")
grep("YES",c,fixed=T)
[1] 3
If I am using fixed = T
, why I am still getting a results when there is no exact match for "YES". I want only exact matches like when I use grep -w
in bash.
The grep() in R is a built-in function that searches for matches to argument patterns within each element of a character vector. The grep() takes pattern and data as main arguments and returns a vector of the indices of the elements of input vector.
grep() function in R Language is used to search for matches of a pattern within each element of the given string. Parameters: pattern: Specified pattern which is going to be matched with given elements of the string. x: Specified string vector.
Details. A 'regular expression' is a pattern that describes a set of strings. Two types of regular expressions are used in R, extended regular expressions (the default) and Perl-like regular expressions used by perl = TRUE . There is also fixed = TRUE which can be considered to use a literal regular expression.
grepl() This is a function in the base package (e.g., it isn't part of dplyr ) that is part of the suite of Regular Expressions functions. grepl uses regular expressions to match patterns in character strings.
This just means that you're matching a string rather than a regular expression, but the string can still be a substring. If you want to match exact cases only, how about
> x=c("HI","NO","YESS") #better not to name variables after common functions
> grep("^YES$",x,fixed=F)
integer(0)
Edit per @nicola: This works b/c ^
means beginning and $
end of string, so ^xxxx$
forces the entire string to match xxxx
.
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