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

2024-03-10

样本数据

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

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

FALSE FALSE TRUE

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

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

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

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

这可以在几行中完成,我可以写一个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

但是有没有更好的方法不涉及使用依赖于位置或顺序的正则表达式strings.to.find.


这不是为了举重,而是为了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

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

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

#[1] FALSE FALSE  TRUE

或者按照@Jota 评论,stri_detect_fixed如果您正在查看的模式应该完全匹配,那么在这里使用会更安全:

library(stringi)
apply(outer(files.in.path, strings.to.find, stri_detect_fixed), 1, all)
# [1] FALSE FALSE  TRUE
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐