How to Use grep() Function in R

The grep() function in R is used to check for matches of characters or sequences of characters in a given string.


grep(pattern, x, = FALSE, value = FALSE)


  1. pattern: It takes a character string containing a regular expression (or character string for fixed = TRUE) to match the given character vector.
  2. x: It is a character vector where matches are sought, or an object can be coerced by as.character to a character vector.
  3. If FALSE, the pattern matching is case sensitive, and if TRUE, the case is ignored during matching.
  4. value: If it is a FALSE, a vector containing the (integer) indices of the matches determined by grep() is returned, and if TRUE, a vector containing the matching elements is returned.

Return Value

It returns a vector of the indices of the elements of x that yielded a match.

Example 1: How to Use grep() function

Let’s search for the character “i” in the character string.

Figure of using grep() function in R

rv <- c("Amazon", "Apple", "Netflix", "Spotify")

print(grep("i", rv))


[1] 3  4

Example 2: Passing argument

Figure of passing argument to the grep() function

In the above figure, we are searching for the character “a” in our input character vector. The “a” character does not exist in the input character vector, but “A” exists. Because we are passing “ = TRUE”, that means now, it will look for “a” or “A” and since “A” exists, it will return the index for the vector that contains A.

rv <- c("Amazon", "Apple", "Netflix", "Spotify")

print(grep("a", rv, = TRUE))


[1] 1  2

Example 3: Passing multiple patterns

The grep() function can check for multiple character patterns in the vector of character strings and returns the indices of elements that contain the pattern.

Figure of passing multiple patterns to the grep() function in R

rv <- c("Amazon", "Apple", "Netflix", "Spotify")

print(grep("o|i", rv, = TRUE))


[1] 1  3  4

In this code, the grep() function searches for elements containing either “o” or “i” and returns their indices.

Example 4: Passing the “value = TRUE” argument

If you set the argument value=TRUE, it will return the actual matched elements themselves instead of their indices.

Figure of Passing value = TRUE argument to the grep() function

rv <- c("Amazon", "Apple", "Netflix", "Spotify")

print(grep("o|i", rv, = TRUE, value = TRUE))


[1] "Amazon" "Netflix" "Spotify"

That’s it.

Leave a Comment