r语言 - 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)
    }

非常感谢您的帮助。

对于精确匹配,请使用值匹配(%in%(

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

一个简单的基础r解决方案是:

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

最新更新