grepl() Function in R

grepl() searches for matches in a string and tells us if a specific pattern is inside that string. It returns a boolean value: TRUE or FALSE.

For example, if I have a string “Bruce Wayne” and I want to find if the letter “z” is in the string, grepl() will return FALSE as it doesn’t contain that character. This guide will explain how to use the grepl() function in R.

Syntax

grepl(pattern, x)

Arguments

  • pattern = regular expression or string
  • x = string or a character vector

Example 1: grepl() function with a string

In this example, we use the grepl() function to check if a character pattern is inside a string.

#creating a string
my_string <- 'I love R programming!'
#searching for a match of a string
grepl('!', my_string)
grepl('z', my_string)
grepl('1', my_string)
grepl('R', my_string)

Output

[1] TRUE
[1] FALSE
[1] FALSE
[1] TRUE

Example 2: grepl() function with a vector

In this example, the grepl() function will search for a character pattern in each element inside the vector. Then, it will return a logical value for each of the elements.

#creating a string
my_vector <- c('Tech', 'TechObservatory', 'TechObs', 'TO')
#searching for a match of a string vector
grepl('Tech', my_vector)
grepl('Obs', my_vector)

Output

[1] TRUE TRUE TRUE FALSE
[1] FALSE TRUE TRUE FALSE

Leave a Comment