The str_detect() function from the stringr in R is “used to detect the presence or absence of a specific pattern in a string.”
Syntax
str_detect(string, pattern, negate = FALSE)
Parameters
- string: It is a character vector.
- pattern: It is the pattern to look for.
- negate: If TRUE, return non-matching elements.
Example 1: Using str_detect() function with String
library(stringr)
fruits <- c("apple pie", "banana split", "cherry tart", "apple juice")
result <- str_detect(fruits, "apple")
print(result)
Output
[1] TRUE FALSE FALSE TRUE
Example 2: Using Regular Expressions
You can detect if any strings in a vector start with the letter “a”.
library(stringr)
fruits <- c("apple", "banana", "avocado", "cherry")
result <- str_detect(fruits, "^a")
print(result)
Output
[1] TRUE FALSE TRUE FALSE
Example 3: Case-Insensitive Detection
Detect the word “apple”, irrespective of its case.
library(stringr)
fruits <- c("Apple pie", "banana split", "APPLE juice", "cherry tart")
result <- str_detect(fruits, regex("apple", ignore_case = TRUE))
print(result)
Output
[1] TRUE FALSE TRUE FALSE
Example 4: Using str_detect() with Vector
library(stringr)
# Create a vector of sentences
sentences <- c(
"The rain in Spain falls mainly on the plain.",
"It was a sunny day.",
"Raindrops keep falling on my head.",
"I don't have an umbrella."
)
# Use str_detect() to find sentences containing the word "rain"
contains_rain <- str_detect(sentences, "rain")
# Print the result
print(contains_rain)
Output
[1] TRUE FALSE FALSE FALSE
Example 5: Using a str_detect() function with Data Frame
# Load the necessary libraries
library(stringr)
library(dplyr) # For data manipulation
# Create a data frame of books
books <- data.frame(
title = c(
"The Magic of Thinking Big",
"How to Win Friends and Influence People",
"The Magic Mountain",
"The Art of War",
"The Secret Magic"
),
author = c(
"David J. Schwartz",
"Dale Carnegie",
"Thomas Mann",
"Sun Tzu",
"Unknown"
)
)
# Use str_detect() to filter rows with
# titles containing the word "magic" (case-insensitive)
magic_books <- books %>%
filter(str_detect(title, regex("magic", ignore_case = TRUE)))
# Print the result
print(magic_books)
Output
That’s it!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.