过滤至少有两个模式匹配的位置

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

我在data.table中有很多文本数据。我有几个我感兴趣的文本模式。我想要对表进行子集化,以便显示与至少两个模式匹配的文本。

由于某些模式已经是/或者像"paul|john"这样的事实,这使事情变得更加复杂。

我想我要么想要一个直接表示基于该子集的表达式,或者如果我可以计算模式出现的次数,那么我可以将其用作子集的工具。我已经看到了计算模式出现次数的方法,但没有计算信息与原始数据集中的ID明确关联的位置,如果这有意义的话。

目前,我能想到的最好的方法是为每个模式的data.table添加一列,检查每个模式是否单独匹配,然后对模式的总和进行过滤。这看起来很复杂,所以我希望有更好的方法,因为有很多模式需要检查!

示例数据

text_table <- data.table(ID = (1:5), text = c("lucy, sarah and paul live on the same street",
                                              "lucy has only moved here recently",
                                              "lucy and sarah are cousins",
                                              "john is also new to the area",
                                              "paul and john have known each other a long time"))
text_patterns <- as.character(c("lucy", "sarah", "paul|john"))

使用示例数据,我希望子集数据中的ID为1和3。

谢谢你的帮助!

r data.table subset
1个回答
2
投票

我们可以使用paste|'text_patterns',在'str_count'中使用它作为模式来获取匹配子字符串的计数,并检查它是否大于1来过滤data.table的行。

library(data.table)
text_table[str_count(text, paste(text_patterns, collapse="|")) >1]
#    ID                                            text
#1:  1    lucy, sarah and paul live on the same street
#2:  3                      lucy and sarah are cousins
#3:  5 paul and john have known each other a long time

Update

如果我们需要将每个'text_pattern'视为固定模式,我们循环遍历模式,检查模式是否存在(str_detect)并使用sum获取所有模式的+以创建用于对行进行子集化的逻辑向量

i1 <- text_table[, Reduce(`+`, lapply(text_patterns, 
       function(x) str_detect(text, x))) >1]
text_table[i1]
#    ID                                         text
#1:  1 lucy, sarah and paul live on the same street
#2:  3                   lucy and sarah are cousins
© www.soinside.com 2019 - 2024. All rights reserved.