And*_*rie 41
是的你可以.在|
一个grep
模式具有相同的含义or
.因此,您可以使用模式来测试"001|100|000"
您的模式.同时,grep
是矢量化的,所以所有这一切都可以一步完成:
x <- c("1100", "0010", "1001", "1111")
pattern <- "001|100|000"
grep(pattern, x)
[1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
这将返回一个索引,其中包含哪些向量包含匹配模式(在本例中为前三个).
有时,使用逻辑向量可以更方便地告诉您向量中的哪些元素匹配.然后你可以使用grepl
:
grepl(pattern, x)
[1] TRUE TRUE TRUE FALSE
Run Code Online (Sandbox Code Playgroud)
有关?regex
R中正则表达式的帮助,请参阅
编辑:
为避免手动创建模式,我们可以使用paste
:
myValues <- c("001", "100", "000")
pattern <- paste(myValues, collapse = "|")
Run Code Online (Sandbox Code Playgroud)
这是一个使用stringr
包的解决方案
require(stringr)
mylist = c("1100", "0010", "1001", "1111")
str_locate(mylist, "000|001|100")
Run Code Online (Sandbox Code Playgroud)