What is the grep() function in R?
Overview
The grep() function in R is used to check for matches of characters or sequences of characters in a given string.
Syntax
grep(pattern, x, ignore.case=TRUE/FALSE, value=TRUE/FALSE)
Parameter(s)
pattern: The character or sequence of characters that will be matched against specified elements of the string.x: The specified string vector.ignore.case: IfTRUE(i.e. it finds a match), the code ignores case (upper or lowercase).value: IfTRUE, it returns the vector of the matching elements; otherwise, it returns the indices vector.
Example code
Let’s use the grep() function to find matching characters or sequences of characters of a string.
# Creating string vectorx <- c("CAR", "car", "Bike", "BIKE")# Calling grep() functiongrep("car", x)grep("Bike", x)grep("car", x, ignore.case = FALSE)# to return the vector indices of both matching elementsgrep("Bike", x, ignore.case = TRUE)# to return matching elementsgrep("car", x, ignore.case = TRUE, value = TRUE)
Explanation
- Line 2: We create a string vector
x. - Lines 5 & 6: We call the
grep()function with two parameters,'car'as apatternandxas a specified string vector. - Line 7: We call the
grep()function withignore.case=FALSEto check case. - Line 10: We call the
grep()function withignore.case=TRUEto ignore case. - Line 14: We call the
grep()function withvalue=TRUEto return matching elements.