【发布时间】:2017-01-03 13:45:29
【问题描述】:
我有一组陈述
statement <- as.matrix(c("the cat sat on the mat",
"the dog ran up the hill",
"the dog ran up the hill to the mat"))
和关键字列表
keywords <- as.matrix(c("cat", "mat", "dog", "hill"))
我想在我的关键字列表中搜索语句并标记出现的关键字,即有结果
statement keywords
the cat sat on the mat cat, mat
the dog ran up the hill dog, hill
the dog ran up the hill to the mat dog, hill, mat
我在想我能做到的一种方法是像使用 grep 一样
statement[grep("cat", statement$V1, ignore.case = TRUE), "keywords"] <- "cat"
statement[grep("mat", statement$V1, ignore.case = TRUE), "keywords"] <- "mat"
... 等等,但首先,这不会为我标记所有出现的关键字。其次,如果我试图找到一种方法,当我有一个大列表时,比如说 1000 个关键字和 500 个语句,它只会变得笨拙。
您对此有何建议?有没有使用 grep 的方法或者是否有任何包可以挖掘文本并从预定列表中返回关键字?
谢谢!
【问题讨论】:
-
这些必须是矩阵对象吗?或者向量就足够了?
-
@benjamin 向量在这种情况下就足够了
-
@DarshanBaral 谢谢!这真的很有帮助
标签: r string-matching