Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding grep with fixed = T in R

Tags:

r

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.

like image 467
GabrielMontenegro Avatar asked Mar 01 '16 14:03

GabrielMontenegro


People also ask

How does grep work in R?

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.

What does the grep () function do?

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.

Can I use regex in R?

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.

What package is Grepl?

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.


1 Answers

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.

like image 197
Philip Avatar answered Sep 30 '22 01:09

Philip