📜  在 R 编程中查找向量或矩阵中的字符串匹配项 – str_detect()函数

📅  最后修改于: 2022-05-13 01:54:46.125000             🧑  作者: Mango

在 R 编程中查找向量或矩阵中的字符串匹配项 – str_detect()函数

R语言中的str_detect()函数用于检查子字符串的指定匹配是否存在于原始字符串中。它将针对向量或矩阵的每个元素找到的匹配返回 TRUE,否则返回 FALSE。

Note: This function uses 'stringr' Library.

示例 1:

# 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)

输出:

[1]  TRUE FALSE FALSE FALSE

示例 2:

# 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)

输出:

,, 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