R:简单的关键字检测

时间:2017-08-02 21:44:51

标签: r stringr grepl

我想检查一组&#34;关键字&#34;中是否任何;出现在一个字符串中。因此,对于下面的&#34; text&#34; ,结果应为TRUE(或1),对于 text_2 ,结果应为FALSE(或0)。< / p>

keywords <- c("one", "two", "three", "four") #set of keywords
text <- "Blah blah one blah two" 
text_2 <- "Blah blah" 

我在str_detect上尝试了一些变化,但是我被卡住了。

因此,例如,我知道我没有正确使用此功能,但是:

> keywords <- c("motor", "car", "ford") #list of keywords
> text <- "I am looking to buy a ford" #string I'd like to check
> ifelse(str_detect(text, pattern = keywords), 1, 0)
[1] 0 0 1

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

试试这个......

any(sapply(keywords,grepl,text))
[1] TRUE

any(sapply(keywords,grepl,text_2))
[1] FALSE