【问题标题】:gsub function, exact match of the patterngsub 函数,模式的完全匹配
【发布时间】:2017-06-27 18:11:20
【问题描述】:

我有一个包含在名为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)
    }

非常感谢您的帮助。

【问题讨论】:

    标签: r text gsub


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 非常感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多