如何删除数据框中的多个管道?

时间:2017-06-13 17:58:21

标签: r string dplyr stringr tidyverse

这是一个简单的例子

library(dplyr)
library(stringr)

    > dataf <- data_frame(text = c('this is a pip||e |' ,
+                              'this is |||'))
> dataf
# A tibble: 2 x 1
                text
               <chr>
1 this is a pip||e |
2        this is |||

我想用空字符串替换数据中的所有管道。基本上我希望它们消失。但是,我一次只能摆脱其中一个:

     > dataf %>% mutate(text = str_replace(text, '\\|+', ""))
# A tibble: 2 x 1
              text
             <chr>
1 this is a pipe |
2         this is

这里有什么问题? 谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用str_replace_all中的stringr删除所有匹配的模式:

dataf %>% mutate(text = str_replace_all(text, '\\|', ""))

# A tibble: 2 × 1
#            text
#           <chr>
#1 this is a pipe
#2       this is