The grep()
function in R is used to check for matches of characters or sequences of characters in a given string.
grep(pattern, x, ignore.case=TRUE/FALSE, value=TRUE/FALSE)
pattern
: The character or sequence of characters that will be matched against specified elements of the string.x
: The specified string vector.ignore.case
: If TRUE
(i.e. it finds a match), the code ignores case (upper or lowercase).value
: If TRUE
, it returns the vector of the matching elements; otherwise, it returns the indices vector.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)
x
.grep()
function with two parameters, 'car'
as a pattern
and x
as a specified string vector.grep()
function with ignore.case=FALSE
to check case.grep()
function with ignore.case=TRUE
to ignore case.grep()
function with value=TRUE
to return matching elements.