Use grep and grepl to find if a word or pattern exists in text. They help you search inside lists or strings easily.
grep and grepl in 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.
words <- c("apple", "banana", "grape", "pineapple") grep("apple", words)
grepl("apple", words)grep("apple", words, value = TRUE)grepl("APPLE", words, ignore.case = TRUE)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.
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)
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.
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.