R语言 寻找向量或矩阵中的字符串匹配 – str_detect() 函数
R语言中的 str_detect() 函数用于检查原始字符串中是否存在指定的子串匹配。如果发现匹配,它将返回 “true”,否则将返回 “false”,因为矢量或矩阵中的每个元素都存在。
注意: 该函数使用 “stringr “库。
语法: str_detect(string, pattern)
参数:
string: 指定的字符串
pattern: 要匹配的图案
例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