2017-08-02 46 views
1

我想检查是否有任何的一组“关键字”出现在一个字符串中。因此,对于下面的“文本”,结果应该为TRUE(或1),对于text_2,它应该是FALSE(或0)。R:简单的关键字检测

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

尝试......

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

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