R - 查找包含所有字符串/模式的所有向量元素 - str_detect grep

LWR*_*RMS 4 r and-operator stringr grepl

样本数据

files.in.path = c("a.4.0. name 2015 - NY.RDS", 
                  "b.4.0. name 2016 - CA.RDS", 
                  "c.4.0. name 2015 - PA.RDS")
strings.to.find = c("4.0", "PA")
Run Code Online (Sandbox Code Playgroud)

我想要显示包含所有元素的逻辑向量strings.to.find。结果想要:

FALSE FALSE TRUE
Run Code Online (Sandbox Code Playgroud)

此代码将查找包含以下任何一项的元素strings.to.find,即,使用 OR 运算符

str_detect(files.in.path, str_c(strings.to.find, collapse="|")) # OR operator
 TRUE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)

此代码尝试使用 AND 运算符但不起作用。

str_detect(files.in.path, str_c(strings.to.find, collapse="&")) # AND operator
FALSE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)

这在几行中有效,我可以编写一个for循环,该循环将为具有大量strings.to.find

det.1 = str_detect(files.in.path,      "4.0"  )   
det.2 = str_detect(files.in.path,      "PA"  )   
det.all = det.1 & det.2
 FALSE FALSE  TRUE
Run Code Online (Sandbox Code Playgroud)

但是有没有更好的方法不涉及使用依赖于strings.to.find.

Psi*_*dom 5

这不是为了繁重的工作,而是str_detect在字符串和模式上进行了矢量化,因此您可以将它与outer函数结合起来以得到接近的结果:

library(stringr)
outer(files.in.path, strings.to.find, str_detect)

#     [,1]  [,2]
#[1,] TRUE FALSE
#[2,] TRUE FALSE
#[3,] TRUE  TRUE
Run Code Online (Sandbox Code Playgroud)

要检查字符串中是否存在所有模式,结果矩阵的每一行applyall逻辑运算符:

apply(outer(files.in.path, strings.to.find, str_detect), 1, all)

#[1] FALSE FALSE  TRUE
Run Code Online (Sandbox Code Playgroud)

或者根据@Jota 的评论,stri_detect_fixed如果您正在查看的模式应该完全匹配,则在此处使用会更安全:

library(stringi)
apply(outer(files.in.path, strings.to.find, stri_detect_fixed), 1, all)
# [1] FALSE FALSE  TRUE
Run Code Online (Sandbox Code Playgroud)


use*_*945 3

在网络上搜索“r regex“and operaror””“regex“and operator””会导致R grep:是否有 AND 运算符?、和正则表达式:是否有 AND 运算符?分别。

因此,为了匹配这两种模式,请将字符串连接在一起

str <- paste0("(?=.*", strings.to.find,")", collapse="") 
grepl(str, files.in.path, perl=TRUE)
Run Code Online (Sandbox Code Playgroud)

正如 Jota 在评论中提到的,通过匹配“4.0”,这也将匹配其他刺痛,因为句点是一个元字符。一种解决方法是转义模式字符串中的句点,即strings.to.find = c( "PA", "4\\.0")