2017-05-17 9 views
0

이 질문에 대한 해결책은 Python/Java에서만 발견되었습니다.문자열에 단어 목록 중 적어도 n 단어가 포함되어 있는지 확인하십시오. R

저는 보도 자료와 해당 날짜가있는 data.frame을 보유하고 있습니다. 각 기사를 확인하고 싶은 키워드 목록이 있습니다. 난 단지 단어 중 하나가 문서에 포함되어 있는지 확인하려면

df <- data.frame(c("2015-05-06", "2015-05-07", "2015-05-08", "2015-05-09"), 
       c("Articel does not contain a key word", "Articel does contain the key word revenue", "Articel does contain two keywords revenue and margin","Articel does not contain the key word margin")) 
colnames(df) <- c("date","article") 

key.words <- c("revenue", "margin", "among others") 

나는 멋진 해결책을했다 :

article.containing.keyword <- filter(df, grepl(paste(key.words, collapse="|"), df$article)) 

이 잘 작동하지만, 사실은 무엇을 찾고 예를 들어, 기사가 적어도 n = 2 개의 키워드를 포함해야만 필터로 선택 될 수 있습니다. 예를 들어, "n 개의 단어가 필터링되어야합니다."라는 문구를 설정할 수있는 솔루션입니다. 원하는 출력은 다음과 같이 싶습니다

date  article 
3 2015-05-08 Articel does contain two keywords revenue and margin 
+1

'sapply rowSums ((key.words를 , grepl, df $ article))> = 2'? –

+0

@docendo discimus 당신의 솔루션은 나를 위해 잘 작동합니다! – Constantin

답변

1

당신은 사용할 수 stringr::str_count :

이런 식으로 필터링 번역 될 수
str_count(df$article, paste(key.words, collapse="|")) 
[1] 0 1 2 1 

:

article.containing.keyword <- dplyr::filter(df, str_count(df$article, paste(key.words, collapse="|")) >= 2) 
     date            article 
1 2015-05-08 Articel does contain two keywords revenue and margin