我想从多个字符向量中删除多个模式。目前我要去:
a.vector <- gsub("@\\w+", "", a.vector)
a.vector <- gsub("http\\w+", "", a.vector)
a.vector <- gsub("[[:punct:]], "", a.vector)
等等。
这很痛苦。我正在看这个问题&amp;回答: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" `
答案 0 :(得分:1)
尝试使用|
组合您的子模式。例如
>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
变体之一
答案 1 :(得分:0)
如果您要查找的多个模式是固定的并且不会因具体情况而改变,您可以考虑创建一个将所有模式组合成一个超级正则表达式模式的连接正则表达式。
对于您提供的示例,您可以尝试:
removePat <- "(@\\w+)|(http\\w+)|([[:punct:]])"
a.vector <- gsub(removePat, "", a.vector)
答案 2 :(得分:0)
我知道这个答案还很晚,但这是因为我不喜欢手动在grep
函数中列出删除模式(请参见此处的其他解决方案)。我的想法是预先设置模式,将其保留为字符向量,然后使用regex
分隔符"|"
粘贴它们(即“需要”时):
library(stringr)
remove <- c("@\\w+", "http\\w+", "[[:punct:]]")
a.vector <- str_remove_all(a.vector, paste(remove, collapse = "|"))
是的,它的确与此处的其他答案相同,但是我认为我的解决方案允许您保留原始的“字符去除向量” remove
。
答案 3 :(得分:0)
我有一个带有陈述“我的最终分数”的向量,我想保留final一词并删除其余的词。根据玛丽安的建议,这对我有用:
str_remove_all(“我的最终成绩”,“我的得分”)
请注意:“我的最终成绩”只是一个例子。我正在处理媒介。