我有一个data.frame,其中包含包含客户数字路径的列(请参见下文)。在每一行中,我都想将>和_referral之间的所有文本替换为Referral。
例如下面的3行
bing_cpc>uswitch.com_referral
bing_cpc>money.co.uk_referral
bing_cpc>moneysupermarket.com_referral>google_organic>moneysupermarket.com_referral>google_cpc>google_cpc
应该是
bing_cpc>Referral
bing_cpc>Referral
bing_cpc>Referral>google_organic>Referral>google_cpc>google_cpc
有什么主意吗? 谢谢
答案 0 :(得分:0)
尝试:
df$col <- gsub(">.*referral", ">Referral", df$col)
答案 1 :(得分:0)
您的问题比看起来要棘手,因此值得详细解答。首先,让您将示例放在向量中:
exStrg <- c(
'bing_cpc>uswitch.com_referral',
'bing_cpc>money.co.uk_referral',
'bing_cpc>moneysupermarket.com_referral>google_organic>moneysupermarket.com_referral>google_cpc>google_cpc'
)
您想要的是将模式'> xxxxx_referral'之后的所有内容替换为'> Referral'。 gsub
是用于此功能,立即模式为'>。* _ referral',点表示“任何字符”,星号表示“随时发生”。但是*
和+
通配符是贪婪的,所以会发生这种情况:
> gsub(pattern = '>.*_referral', replacement = '>Referral', exStrg)
[1] "bing_cpc>Referral"
[2] "bing_cpc>Referral"
[3] "bing_cpc>Referral>google_cpc>google_cpc"
表达式将在第一个“>”和最后一个“ _referral”之间取任何值。您可以使用?
使通配符变得懒惰;可以识别出您的模式的多次出现,但仍将所有内容都放在中间:
> gsub('>.*?_referral', '>Referral', exStrg)
[1] "bing_cpc>Referral"
[2] "bing_cpc>Referral"
[3] "bing_cpc>Referral>Referral>google_cpc>google_cpc"
您需要的是将任何后续的'>'表示为否定字符:
> gsub('>[^>]*_referral', '>Referral', exStrg)
[1] "bing_cpc>Referral"
[2] "bing_cpc>Referral"
[3] "bing_cpc>Referral>google_organic>Referral>google_cpc>google_cpc"