我正在尝试从以下数组中使用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!"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句