R grepl() Function

The grepl() function in R is used for pattern matching and searching within strings. It’s a variation of the grep() function, where grepl() returns a logical vector suggesting whether a pattern is found in each element of a character vector.

Syntax

grepl(pattern, x, ignore.case = FALSE, perl = FALSE,
      fixed = FALSE, useBytes = FALSE)

Parameters

  1. pattern: It is a regular expression or string for fixed=TRUE
  2. x: It is a string, the character vector
  3. perl: Logical. Should Perl-compatible regexps be used? Has priority been overextended?
  4. fixed: It is logical. If the TRUE, the pattern is a string to be matched. Overrides all conflicting arguments
  5. useBytes: It is logical. If TRUE, the matching is done byte-by-byte rather than character-by-character.

Return value

It returns TRUE if a string contains the pattern; otherwise, it is FALSE.

Example 1: Searching for simple patterns in character vectors

Visual representation of the grepl() Function in R

rv <- c("KHUSHI", "KRUNAL", "MATE", "AUS")

grepl("K", rv)

Output

[1] TRUE TRUE FALSE FALSE

Example 2: Using regular expressions

Using regular expressions with the grepl() function

In the figure, we are checking if the string sv contains any numeric digits. If there is a numeric digit, it returns TRUE; otherwise, it is FALSE.

sv <- "Infosys is currently trading at 1435 Rs."

op <- grepl("\\d+", sv)

print(op)

Output

[1] TRUE

Example 3: Passing ignore.case argument

To ignore the cases of the letters while searching for patterns, pass the ignore.case = TRUE. It will ignore whether it is in capital or small letters in the string.

Ignoring case while searching using grepl() function
Figure 3: Passing ignore.case = TRUE to the grepl() function
rv <- c("khushi", "KRUNAL", "MATE", "AUS")
grepl("K", rv, ignore.case = T)

Output

[1] TRUE TRUE FALSE FALSE

If we pass ignore.case = F or FALSE, it will only return the TRUE on the second position.

Passing ignore.case = F or FALSE
Figure 4: ignore.case = F or FALSE
rv <- c("khushi", "KRUNAL", "MATE", "AUS")

grepl("K", rv, ignore.case = F)

Output

[1] FALSE TRUE FALSE FALSE

You will find all the information about the grepl() method in the below image in RStudio.

Use grepl() function in RStudio
Figure 5: Use grepl() function in RStudio

The functions like grep(), grepl(), regexpr(), gregexpr(), and regexec() search for matches to argument patterns within every item of a character vector.

Leave a Comment