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:
# R Program to illustrate # the use of str_detect function # Loading library library(stringr) # Creating vector x < - c( "Beginner" , "Hello" , "Welcome" , "For" ) # Pattern to be matched pat < - "Beginner" # Calling str_detect() function str_detect(x, pat) |
Output:
[1] TRUE FALSE FALSE FALSE
Example 2:
# R Program to illustrate # the use of str_detect function # Loading library library(stringr) # Creating vector x1 < - c( "Beginner" , "Beginner" , "Welcome" , "Beginner" ) x2 < - c( "Beginner" , "Hello" , "Beginner" ) result < - array(c(x1, x2), dim = c( 2 , 2 , 2 )) # Pattern to be matched pat < - "Beginner" # Printing Matrix result # Calling str_detect() function str_detect(result, pat) |
Output:
,, 1 [, 1] [, 2] [1, ] "Beginner" "Welcome" [2, ] "Beginner" "Beginner",, 2 [, 1] [, 2] [1, ] "Beginner" "Beginner" [2, ] "Hello" "Beginner" [1] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE
Contact Us