【问题标题】:Removing multiple words from a string using a vector instead of regexp in R使用向量而不是R中的正则表达式从字符串中删除多个单词
【发布时间】:2019-05-10 18:46:13
【问题描述】:

我想从 R 中的字符串中删除多个单词,但想使用字符向量而不是正则表达式。

例如,如果我有字符串

"hello how are you" 

并想删除

c("hello", "how")

我会回来的

" are you"

我可以从stringrstr_remove() 亲密接触

"hello how are you" %>% str_remove(c("hello","how"))
[1]  "how are you"   "hello  are you"

但是我需要做一些事情来把它变成一个字符串。有没有一个函数可以一次性完成所有这些操作?

【问题讨论】:

标签: r string vector stringr


【解决方案1】:

我们可以使用| 作为正则表达式 OR

library(stringr)
library(magrittr)
pat <- str_c(words, collapse="|")
"hello how are you" %>% 
      str_remove_all(pat) %>%
      trimws
#[1] "are you"

数据

words <- c("hello", "how")

【讨论】:

  • 改进建议:paste+collapse = "|"在单词向量上......所以你不必重新输入everyting?
  • 好主意——非常聪明!我很惊讶这样的事情没有在其中一个字符串包中实现,但这是一个简单的解决方法。
  • 对于str_remove,默认解释为regex。不过,您可以使用 fixed 进行包装。但是,问题在于它期望模式和字符串具有相同的长度。 "hello how are you" %&gt;% str_remove_all(fixed(words)) [1] " how are you" "hello are you"
【解决方案2】:

base R 的可能性可能是:

x <- "hello how are you"   
trimws(gsub("hello|how", "\\1", x))

[1] "are you"

或者如果你有更多的话,@Wimpel提出的一个聪明的想法:

words <- paste(c("hello", "how"), collapse = "|")
trimws(gsub(words, "\\1", x))

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2022-01-13
    • 2016-03-01
    • 1970-01-01
    • 2019-12-08
    相关资源
    最近更新 更多