样本数据
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/