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

标签 r stringr grepl and-operator

样本数据

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

关于R - 查找包含所有字符串/模式的所有向量元素 - str_detect grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39439238/

相关文章:

r - 带有重叠子串的 str_count

用于捕获时间的正则表达式在冒号前没有两位数,只有一位

r - 在R中将文本框保存为pdf

Read.csv() 抛出错误

r - dplyr::end_with 和区分大小写

r - str_split 和 str_trim 并在 R 中简化

r - R data.table 中的复杂总和,涉及查看其他列

R:如何删除包含特定字符模式的字符串?

r - 如何在 R 中删除具有模式的行?

r - 检查字符串是否包含向量 [R] 中项目以外的任何内容