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 |
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 |
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 |
grepl("x", vec) # Apply grepl function # FALSE TRUE TRUE FALSE FALSE