What is the grep() Function in R

The grep() is a built-in R function that checks for matches of characters or sequences of characters in a given string”.

Syntax

grep(pattern, x, ignore.case = FALSE, value = FALSE)

Arguments

pattern: It takes a character string containing a regular expression (or character string for fixed = TRUE) to match the given character vector.

x: It is a character vector where matches are sought, or an object can be coerced by as.character to a character vector.

ignore.case: If FALSE, the pattern matching is case sensitive, and if TRUE, the case is ignored during matching.

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

The grep() function returns a vector of the indices of the elements of x that yielded a match.

Example 1: Use of the grep() function

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

data <- c("Newgen", "Happiest Minds", "Tata Elxsi", "LTTS")

print(grep("a", data))

Output

[1] 2 3

In this example, “a” is matched with Happiest Minds and Tata Elxsi. So, it returns the index of these strings.

It searches for matches of the input character “a” within the example vector data and returns the indices of vector elements that contain the character “a”.

Example 2: Passing ignore.case and value parameters

x <- c("BMW", "audi", "MERCEDEZ", "bmw")

grep("mercedez", x, ignore.case = TRUE, value = TRUE)
grep("B", x, ignore.case = TRUE, value = TRUE)
grep("audi", x, ignore.case = FALSE, value = FALSE)
grep("BMW", x, ignore.case = FALSE, value = FALSE)

Output

[1] "MERCEDEZ"
[1] "BMW" "bmw"
[1] 2
[1] 1

Example 3: Passing multiple patterns to the grep() function

The grep() function checks for multiple character patterns in our vector of character strings.

data <- c("Newgen", "Happiest Minds", "Tata Elxsi", "LTTS")

print(grep("a|t", data))

Output

[1] 2  3

In this example, we search for a or t in a string, finding two strings containing both character vectors.

That’s it.

Leave a Comment