【发布时间】:2019-04-16 10:13:14
【问题描述】:
我在 data.table 中有很多文本数据。我有几个我感兴趣的文本模式。我设法对表格进行了子集化,以便它显示与至少两个模式匹配的文本(相关问题here)。
我现在希望每个匹配有一行,并带有一个标识匹配的附加列 - 因此,除了该列之外,存在多个匹配的行将是重复的。
感觉这应该不会太难,但我很挣扎!我模糊的想法可能是计算模式匹配的数量,然后多次复制行......但是我不完全确定如何为每个不同的模式获取标签......(也不确定那是无论如何都非常有效)。
感谢您的帮助!
示例数据
library(data.table)
library(stringr)
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"))
# Filtering the table to just the IDs with at least two pattern matches
text_table_multiples <- text_table[, Reduce(`+`, lapply(text_patterns,
function(x) str_detect(text, x))) >1]
理想输出
required_table <- data.table(ID = c(1, 1, 1, 2, 3, 3, 4, 5),
text = c("lucy, sarah and paul live on the same street",
"lucy, sarah and paul live on the same street",
"lucy, sarah and paul live on the same street",
"lucy has only moved here recently",
"lucy and sarah are cousins",
"lucy and sarah are cousins",
"john is also new to the area",
"paul and john have known each other a long time"),
person = c("lucy", "sarah", "paul or john", "lucy", "lucy", "sarah", "paul or john", "paul or john"))
【问题讨论】:
标签: r data.table