0
0
R Programmingprogramming~5 mins

grep and grepl in R Programming

Choose your learning style9 modes available
Introduction

Use grep and grepl to find if a word or pattern exists in text. They help you search inside lists or strings easily.

You want to find which words in a list contain a certain pattern.
You need to check if a sentence has a specific word.
You want to filter data rows that include a keyword.
You want to know if a pattern appears anywhere in your text.
You want to get the positions of matching words in a list.
Syntax
R Programming
grep(pattern, x, ignore.case = FALSE, value = FALSE)
grepl(pattern, x, ignore.case = FALSE)

pattern is the text or regular expression you want to find.

x is the vector of strings to search in.

ignore.case lets you ignore uppercase/lowercase differences.

value = TRUE in grep returns matching strings instead of their positions.

Examples
Find positions of words containing "apple".
R Programming
words <- c("apple", "banana", "grape", "pineapple")
grep("apple", words)
Returns TRUE or FALSE for each word if it contains "apple".
R Programming
grepl("apple", words)
Returns the actual words that contain "apple".
R Programming
grep("apple", words, value = TRUE)
Checks for "APPLE" ignoring case differences.
R Programming
grepl("APPLE", words, ignore.case = TRUE)
Sample Program

This program searches for the pattern "Cat" in a list of words. It shows the positions where "Cat" appears, a TRUE/FALSE list for each word, the matching words themselves, and a case-insensitive check.

R Programming
words <- c("Cat", "Dog", "Caterpillar", "Bird")
positions <- grep("Cat", words)
matches <- grepl("Cat", words)
cat_words <- grep("Cat", words, value = TRUE)
ignore_case <- grepl("cat", words, ignore.case = TRUE)

print(positions)
print(matches)
print(cat_words)
print(ignore_case)
OutputSuccess
Important Notes

grep returns positions by default, but you can get matching values with value = TRUE.

grepl returns a logical vector (TRUE/FALSE) for each element.

Both functions support regular expressions for advanced pattern matching.

Summary

grep finds positions or values matching a pattern.

grepl tells you TRUE or FALSE if a pattern exists in each element.

Use ignore.case = TRUE to ignore letter case differences.