【发布时间】:2018-10-25 15:33:46
【问题描述】:
我有两个文件,一个包含关键字(大约 2,000 行),另一个包含文本(大约 770,000 行)。关键字文件如下所示:
Event Name Keyword
All-day tabby fest tabby, all-day
All-day tabby fest tabby, fest
Maine Coon Grooming maine coon, groom
Maine Coon Grooming coon, groom
keywordFile <- tibble(EventName = c("All-day tabby fest", "All-day tabby fest", "Maine Coon Grooming","Maine Coon Grooming"), Keyword = c("tabby, all-day", "tabby, fest", "maine coon, groom", "coon, groom")
文本文件如下所示:
Description
Bring your tabby to the fest on Tuesday
All cats are welcome to the fest on Tuesday
Mainecoon grooming will happen at noon Wednesday
Maine coons will be pampered at noon on Wednesday
text <- tibble(Description = c("Bring your tabby to the fest on Tuesday","All cats are welcome to the fest on Tuesday","Mainecoon grooming will happen at noon Wednesday","Maine coons will be pampered at noon on Wednesday")
我想要的是遍历文本文件并查找模糊匹配(必须包括“关键字”列中的每个单词)并返回一个显示 TRUE 或 False 的新列。如果这是真的,那么我想要第三列显示事件名称。所以看起来像:
Description Match? Event Name
Bring your tabby to the fest on Tuesday TRUE All-day tabby fest
All cats are welcome to the fest on Tuesday FALSE
Mainecoon grooming will happen at noon Wednesday TRUE Maine Coon Grooming
Maine coons will be pampered at noon on Wednesday FALSE
感谢 Molx (How can I check if multiple strings exist in another string?),我能够使用这样的东西成功地进行模糊匹配(在将所有内容转换为小写之后):
str <- c("tabby", "all-day")
myStr <- "Bring your tabby to the fest on Tuesday"
all(sapply(str, grepl, myStr))
但是,当我尝试模糊匹配整个文件时,我遇到了困难。我尝试过这样的事情:
for (i in seq_along(text$Description)){
for (j in seq_along(keywordFile$EventName)) {
# below I am creating the TRUE/FALSE column
text$TF[i] <- all(sapply(keywordFile$Keyword[j], grepl,
text$Description[i]))
if (isTRUE(text$TF))
# below I am creating the EventName column
text$EventName <- keywordFile$EventName
}
}
我认为将正确的内容转换为向量和字符串时没有问题。我的keywordFile$Keyword 列是一堆字符串向量,而我的text$Description 列是一个字符串。但是我正在努力解决如何正确遍历这两个文件。我得到的错误是
Error in ... replacement has 13 rows, data has 1
以前有人做过这样的事吗?
【问题讨论】:
-
我相信我有 (stackoverflow.com/questions/51733851/…),但是如果您以可重现的格式发布数据,它会更容易提供帮助。查看stackoverflow.com/questions/5963269/…
-
我检查了那里的链接,但是当我尝试实现它时出现错误(模式的长度> 1,只会使用第一个元素)。我已经编辑了我的问题以包含一些代码以及我在运行 for 循环代码时遇到的错误。我希望这有帮助。真的坚持这一点。
标签: r loops matching sapply grepl