我想从多个字符向量中删除多个模式。目前我要做的是:
a.vector <- gsub("@\\w+", "", a.vector)
a.vector <- gsub("http\\w+", "", a.vector)
a.vector <- gsub("[[:punct:]], "", a.vector)等等。
这是痛苦的。我正在看这个问题&答案是:R: gsub, pattern = vector and replacement = vector,但它不能解决问题。
mapply和mgsub都无法正常工作。我做了这些载体
remove <- c("@\\w+", "http\\w+", "[[:punct:]]")
substitute <- c("")mapply(gsub, remove, substitute, a.vector)和mgsub(remove, substitute, a.vector) worked.都不是
a.vector看起来像这样:
[4951] "@karakamen: Suicide amongst successful men is becoming rampant. Kudos for staing the conversation. #mental"
[4952] "@stiphan: you are phenomenal.. #mental #Writing. httptxjwufmfg" 我想要:
[4951] "Suicide amongst successful men is becoming rampant Kudos for staing the conversation #mental"
[4952] "you are phenomenal #mental #Writing" `发布于 2019-06-03 12:48:50
我知道这个答案出现得太晚了,但它源于我不喜欢在grep函数中手动列出删除模式(请参阅此处的其他解决方案)。我的想法是预先设置模式,将它们保留为字符矢量,然后使用regex seperator "|"粘贴它们(即在需要时
library(stringr)
remove <- c("@\\w+", "http\\w+", "[[:punct:]]")
a.vector <- str_remove_all(a.vector, paste(remove, collapse = "|"))是的,这确实与这里的一些其他答案有效地做了相同的事情,但我认为我的解决方案允许您保留原始的“字符删除向量”remove。
发布于 2015-03-14 00:35:10
尝试使用|组合子模式。例如
>s<-"@karakamen: Suicide amongst successful men is becoming rampant. Kudos for staing the conversation. #mental"
> gsub("@\\w+|http\\w+|[[:punct:]]", "", s)
[1] " Suicide amongst successful men is becoming rampant Kudos for staing the conversation #mental"但是,如果您有大量的模式,或者如果应用一个模式的结果与其他模式相匹配,这可能会出现问题。
考虑按照您的建议创建remove向量,然后在循环中应用它
> s1 <- s
> remove<-c("@\\w+","http\\w+","[[:punct:]]")
> for (p in remove) s1 <- gsub(p, "", s1)
> s1
[1] " Suicide amongst successful men is becoming rampant Kudos for staing the conversation #mental"当然,这种方法需要扩展以应用于整个表或向量。但是,如果您将其放入返回最终字符串的函数中,则应该能够将其传递给apply变体之一
发布于 2015-10-24 08:15:11
如果您正在寻找的多个模式是固定的,并且不随情况而改变,您可以考虑创建一个串联的正则表达式,它将所有模式组合成一个超级正则表达式模式。
对于您提供的示例,您可以尝试:
removePat <- "(@\\w+)|(http\\w+)|([[:punct:]])"
a.vector <- gsub(removePat, "", a.vector)https://stackoverflow.com/questions/29036960
复制相似问题