gsub函数,模式的完全匹配

时间:2017-06-27 18:11:21

标签: r text gsub

我有一个名为remove的数据框中包含的单词列表。我想删除text中的所有字词。我想删除确切的单词。

remove <- data.frame("the", "a", "she")
text <- c("she", "he", "a", "the", "aaaa")

for (i in 1:3) {
  text <- gsub(data[i, 1], "", text)
}

附件是返回的结果

#[1] ""   "he" ""   ""   ""

然而,我期待的是

#[1] ""   "he" ""   ""   "aaaa"

我也尝试了以下代码,但它确实返回了预期的结果:

for (i in 1:3) {
    text <- gsub("^data[i, 1]$", "", text)
    }

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

要获得完全匹配,请使用值匹配(%in%

remove<-c("the","a","she") #I made remove a vector too
replace(text, text %in% remove, "")
#[1] ""     "he"   ""     ""     "aaaa"

答案 1 :(得分:1)

简单的基本R解决方案是:

text[!text %in% as.vector(unlist(remove, use.names = FALSE))]
相关问题