當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R語言 str_detect()用法及代碼示例


str_detect()R語言中的函數用於檢查原始字符串中是否存在子字符串的指定匹配項。對於找到的匹配項,它將返回 TRUE,否則針對 Vector 或矩陣的每個元素返回 FALSE。

Note: This function uses 'stringr' Library.
用法: 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



相關用法


注:本文由純淨天空篩選整理自nidhi_biet大神的英文原創作品 Find String Matches in a Vector or Matrix in R Programming – str_detect() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。