2017-10-11 103 views
3

我處理的是如下[R排除關鍵字

Has no anorexia 
    She denies anorexia 
    Has anorexia 
    Positive for Anorexia 

我的目標是排除有話像denies, denied, no,只保留厭食的積極跡象句子句的句子。

最終的結果應該是

 Has anorexia 
    Positive for Anorexia 

我試着用grepl功能

 negation <- c("no","denies","denied") 
    if (grepl(paste(negation,collapse="|"), Anorexia_sentences[j]) == TRUE){ 

    Anorexia_sentences[j] <- NA 

    } 

,這是行不通的這個選項,我認爲沒有在A字no惹下會引起一些問題。任何建議如何解決這個問題,非常感謝。

+3

你缺少'denied'之後的一個報價 – lawyeR

+2

也許'否定<-c(「\\ bno \\ b」,...) –

+0

您不需要循環,if或任何東西只要'denies = grepl (...,Anorexia_sentences); Anoreia_sentences [denies] = NA' – Gregor

回答

4

語料庫庫在長期水平,而不是字符水平有工作像stringr等價物的功能,但工作。這工作:

library(corpus) 
negation <- c("no", "denies", "denied") 
text <- c("Has no anorexia", "She denies anorexia", "Has anorexia", 
      "Positive for Anorexia", "Denies anorexia") 
text[!text_detect(text, negation)] 
## [1] "Has anorexia"   "Positive for Anorexia" 

如果您希望只使用基礎R的解決方案,而不是使用以下:

pattern <- paste0("\\b(", paste(negation, collapse = "|"), ")\\b") 
text[!grepl(pattern, text, ignore.case = TRUE)] 
+0

我會嘗試 –

0

你也可以做到這一點很容易地使用quanteda包。要將角色對象註冊爲句子,您需要標點符號,或者將行分割爲character矢量的元素。然後,我們可以使用char_trimsentences()在標記化時刪除具有特定模式匹配的那些。

library("quanteda") 

readLines(textConnection(txt)) %>% 
    char_trimsentences(exclude_pattern = c("\\bden\\w+\\b|\\bno\\b")) 
##    text3     text4 
##  "Has anorexia" "Positive for Anorexia" 

正則表達式可以保證你將匹配詞與glob模式「巢穴*」和「沒有」作爲一個單詞只(而不是的一部分,沒有惹下。