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: 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.

Example code

Let’s use the grep() function to find matching characters or sequences of characters of a string.

# Creating string vector
x <- c("CAR", "car", "Bike", "BIKE")
# Calling grep() function
grep("car", x)
grep("Bike", x)
grep("car", x, ignore.case = FALSE)
# to return the vector indices of both matching elements
grep("Bike", x, ignore.case = TRUE)
# to return matching elements
grep("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 a pattern and x as a specified string vector.
  • Line 7: We call the grep() function with ignore.case=FALSE to check case.
  • Line 10: We call the grep() function with ignore.case=TRUE to ignore case.
  • Line 14: We call the grep() function with value=TRUE to return matching elements.

Free Resources