grep & grepl Functions in R (Example)

This page shows how to search for pattern in character strings by applying the grep() and grepl() functions in the R programming language.

Example Data

vec <- c("yo", "x", "example", "abcd", "gggg")      # Create example vector

Application of grep Function in R

The grep function returns the index of vector elements containing a certain character pattern:

grep("x", vec)                                      # Apply grep function
# 2 3

Application of grepl Function in R

The grepl function returns a logical vector, indicating which vector elements contain a certain character pattern:

grepl("x", vec)                                     # Apply grepl function
# FALSE  TRUE  TRUE FALSE FALSE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top