在grep中查找模式向量的匹配索引

问题描述 投票:0回答:1

在使用grep时,是否有一种简单的方法可以找到相应的矢量索引?

v=c(123,456,789,651)
pat=c(1,35,47,8)
id=grep(paste0(pat, collapse="|"), v)
v[id]

[1] 123 789 651

我想生成:

pat_id
[1] 1 4 1

所以pat[pat_id]会给我pat中匹配的值。

pat[pat_id]
[1] 1 8 1

在这种情况下不能使用match(),因为字符串必须相同才能算作匹配。

r grep
1个回答
1
投票

我们可以遍历v并使用str_detect,因为它被矢量化以查找模式是否存在于其中任何一个并直接返回索引或向量。

library(stringr)
unlist(sapply(v, function(x) which(str_detect(x, as.character(pat)))))
#[1] 1 4 1

如果最终目标是获得pat向量而不是我们可以直接做到

unlist(sapply(v, function(x) pat[str_detect(x, as.character(pat))]))
#[1] 1 8 1
© www.soinside.com 2019 - 2024. All rights reserved.