使用 gsub 从字符串中删除模式:argument 'pattern' has length > 1 and only the first element will be used

Use gsub to remove pattern from a string: argument 'pattern' has length > 1 and only the first element will be used

我正在尝试使用 gsub 从以下 chr

数组中删除字符串中的模式
articles<-c("RT @name1: hello world", "@nickname1: bye bye guys", 
"RT @name2_surname2: I have no text", "Hello!")

模式仅在以RT开头的字符串中由@:之间的项组成。因此在我们的例子中,模式是:

 "name1"    "name2_surname2"

模式可以通过

获得
pat <- "^RT.*?@(.*?):.*"
res <- gsub(pat,"\1",articles[grepl(pat,articles)])

去掉这个模式后,想要的结果是这样的:

"RT : hello world", "@nickname1: bye bye guys", 
"RT : I have no text", "Hello!"

无论如何,当我使用:

gsub(res,"",articles)

我得到了一个错误的结果:

[1] "RT @: hello world"                  "@nick: bye bye guys"               
[3] "RT @name2_surname2: I have no text" "Hello!"                            
Warning message:
In gsub(res, "", articles) :
  argument 'pattern' has length > 1 and only the first element will be used

我们可以 paste 将模式转换为单个字符串并在 gsub 模式中使用它,因为 pattern 参数未矢量化,即它的长度仅为 1

gsub(paste0("\b(", paste(res, collapse="|"),  ")\b"), "", articles)
#[1] "RT @: hello world"        "@nickname1: bye bye guys" "RT @: I have no text"     "Hello!"      

如果所需的输出如前所述是这样的:

"RT : hello world", "@nickname1: bye bye guys", "RT : I have no text", "Hello!"

那么这个解决方案有效:

首先,您需要更改模式以将 @ 包含在捕获组中:

pat <- "^RT.*?(@.*?):.*"
res <- gsub(pat,"\1",articles[grepl(pat,articles)])

然后,按照@Akrun 的建议,您可以将 res 的两个矢量元素粘贴在一起,这样您就可以将其用作(单个)模式:

gsub(paste0(res, collapse = "|"), "", articles)

这会给你不希望的输出。