Find String Matches in a Vector or Matrix in R Programming – str_detect() Function

str_detect() Function in R Language is used to check if the specified match of the substring exists in the original string. It will return TRUE for a match found otherwise FALSE against each of the element of the Vector or matrix.

Note: This function uses 'stringr' Library.

Syntax: str_detect(string, pattern)

Parameter:
string: specified string
pattern: Pattern to be matched

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R Program to illustrate 
# the use of str_detect function
  
# Loading library
library(stringr)
  
# Creating vector
x <- c("Geeks", "Hello", "Welcome", "For")
  
# Pattern to be matched
pat <- "Geeks"
  
# Calling str_detect() function
str_detect(x, pat)

chevron_right


Output:

[1]  TRUE FALSE FALSE FALSE

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R Program to illustrate 
# the use of str_detect function
  
# Loading library
library(stringr)
  
# Creating vector
x1 <- c("Geeks", "Geeks", "Welcome", "Geeks")
x2 <- c("Geeks", "Hello", "Geeks")
  
result <- array(c(x1, x2), dim = c(2, 2, 2))
  
# Pattern to be matched
pat <- "Geeks"
  
# Printing Matrix
result
  
# Calling str_detect() function
str_detect(result, pat)

chevron_right


Output:

,, 1

     [, 1]    [, 2]     
[1, ] "Geeks" "Welcome"
[2, ] "Geeks" "Geeks",, 2

     [, 1]    [, 2]   
[1, ] "Geeks" "Geeks"
[2, ] "Hello" "Geeks"

[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE



My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.