How to Use str_detect in R for String Pattern Detection
In R, use
str_detect(string, pattern) from the stringr package to check if a string contains a pattern. It returns TRUE if the pattern is found and FALSE otherwise.Syntax
The str_detect() function has two main parts:
- string: The text or vector of texts you want to check.
- pattern: The text pattern or regular expression you want to find.
It returns a logical vector showing TRUE where the pattern is found and FALSE where it is not.
r
str_detect(string, pattern)
Example
This example shows how to check if words contain the letter 'a'. It returns TRUE for words with 'a' and FALSE for those without.
r
library(stringr) words <- c("apple", "banana", "pear", "grape") result <- str_detect(words, "a") print(result)
Output
[1] TRUE TRUE TRUE TRUE
Common Pitfalls
One common mistake is forgetting to load the stringr package before using str_detect(). Another is using incorrect pattern syntax, which can cause unexpected results.
Also, str_detect() is case sensitive by default, so searching for "A" won't match "apple".
r
library(stringr) words <- c("Apple", "banana", "Pear", "grape") # Wrong: case sensitive search str_detect(words, "a") # Right: use regex ignore case str_detect(words, regex("a", ignore_case = TRUE))
Output
[1] FALSE TRUE FALSE TRUE
[1] TRUE TRUE TRUE TRUE
Quick Reference
| Function | Description |
|---|---|
| str_detect(string, pattern) | Returns TRUE if pattern is found in string |
| regex(pattern, ignore_case = TRUE) | Makes pattern search case insensitive |
| library(stringr) | Loads the stringr package needed for str_detect |
Key Takeaways
Use str_detect(string, pattern) to check if a pattern exists in text.
Always load stringr package with library(stringr) before using str_detect.
str_detect returns TRUE or FALSE for each string checked.
Patterns are case sensitive by default; use regex() with ignore_case = TRUE to ignore case.
Check your pattern syntax to avoid unexpected matches.