英文:
Use str_replace() to detect a string with a '+' string
问题
我想清洗sales_method列,使'email'变为'Email','em + call'变为'Email + Call'。但是当我使用str_replace_all()
时,它只能检测和替换'email'。是否有一种方法可以替换其中包含'+'符号的字符串?
我尝试了以下代码:
rep_str = c('email'='Email', 'em + call'='Email + Call')
sales_no_na$sales_method <- str_replace_all(sales_no_na$sales_method, rep_str)
然后结果如下图所示:
英文:
I wanted to clean the sales_method column such that 'email' would go under 'Email' and 'em + call' would go under 'Email + Call'. But when I use str_replace_all()
, it was only able to detect and replace 'email'. Is there a way to replace the string with the '+' sign in it?
I tried
rep_str = c('email'='Email', 'em + call'='Email + Call')
sales_no_na$sales_method <- str_replace_all(sales_no_na$sales_method, rep_str)
which then ended up like this
答案1
得分: 2
你必须使用 \\
转义加号。使用以下代码:
rep_str = c('email'=>'Email', 'em \\+ call'=>'Email + Call')
df$sales_method <- str_replace_all(df$sales_method, rep_str)
> df
# A tibble: 5 × 2
count sales_method
<dbl> <chr>
1 6915 Email
2 4781 Call
3 2203 Email + Call
4 20 Email + Call
5 7 Email
英文:
You have to escape the plus sign using \\
. Use
rep_str = c('email'='Email', 'em \\+ call'='Email + Call')
df$sales_method <- str_replace_all(df$sales_method, rep_str)
> df
# A tibble: 5 × 2
count sales_method
<dbl> <chr>
1 6915 Email
2 4781 Call
3 2203 Email + Call
4 20 Email + Call
5 7 Email
答案2
得分: 0
请尝试以下代码
```r
df %>% mutate(sales_method=str_replace_all(sales_method, c('call'='Call','email'='Email','em'='Email'))) %>%
group_by(sales_method) %>%
summarise(count=sum(count)) %>%
ungroup()
# 一个 tibble: 3 × 2
销售方法 计数
<chr> <dbl>
1 电话 4781
2 电子邮件 6922
3 电子邮件 + 电话 2223
<details>
<summary>英文:</summary>
Please try the below code
```r
df %>% mutate(sales_method=str_replace_all(sales_method, c('call'='Call','email'='Email','em'='Email'))) %>%
group_by(sales_method) %>%
summarise(count=sum(count)) %>% ungroup()
# A tibble: 3 × 2
sales_method count
<chr> <dbl>
1 Call 4781
2 Email 6922
3 Email + Call 2223
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论