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

标签 r string vector stringr

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

例如,如果我有字符串

"hello how are you" 

并想删除

c("hello", "how")

我会回来

" are you"

我可以使用 stringr 中的 str_remove() 来接近

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

但是我需要做一些事情来将其分解为一个字符串。是否有一个函数可以一次调用完成所有这些操作?

最佳答案

我们可以使用 | 来评估正则表达式或

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")

关于使用向量而不是 R 中的正则表达式从字符串中删除多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083274/

相关文章:

python - 通过 RPy 对 lme4.lmer 输出调用方差分析

string - Lua中将字符串分割成相等的 block

java html内容带有多个单双引号

r - 使用 httr 进行网页抓取会出现 xml_nodeset 错误

r - 如何使用神经网络包预测新病例

R 在轴表达式中导出带有 unicode 的 ggplot 对象时崩溃

java - 如何比较两个字符串并用 - 替换不匹配的字母?

c - vector 作为参数 C

c++ - 如何访问 std::vector 迭代器中的 std::map 属性?

c++ - 根据用户输入用字母填充 vector ,并将开始和结束放在四肢上