2017-10-11 70 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模式“巢穴*”和“没有”作为一个单词只(而不是的一部分,没有惹下。