Replace part of string with mutate (in a pipe)

旧街凉风 提交于 2020-08-27 07:52:31

问题


I would like to replace a part of a string (between the first 2 underscores, the first group always being "i") like in the base R example below:

library(dplyr)
library(stringr)

d <- tibble(txt = c("i_0000_GES", "i_0000_OISO", "i_0000_ASE1333"),
            repl = c("1111", "1111", "2222"))

str_sub(d$txt, 3, 6) <- d$repl
d

# A tibble: 3 x 2
# txt            repl 
# <chr>          <chr>
# 1 i_1111_GES     1111 
# 2 i_1111_OISO    1111 
# 3 i_2222_ASE1333 2222  

How can I do that either using str_sub<- or another stringr-function?


回答1:


Here is one way using str_sub<- in a pipe.

d %>%
  mutate(txt = `str_sub<-`(txt, 3, 6, value = repl))
## A tibble: 3 x 2
#  txt            repl 
#  <chr>          <chr>
#1 i_1111_GES     1111 
#2 i_1111_OISO    1111 
#3 i_2222_ASE1333 2222 

Note that argument value is the last, so it must be passed assigned to its name.




回答2:


You can probably do:

d %>%
 mutate(txt = str_replace(txt, str_sub(txt, 3, 6), repl))

  txt            repl 
  <chr>          <chr>
1 i_1111_GES     1111 
2 i_1111_OISO    1111 
3 i_2222_ASE1333 2222

Here you first substring and then replace this substring with repl.

Or:

d %>%
 mutate(txt = {str_sub(txt, 3, 6) <- repl; txt})



回答3:


With base R we can use substring

substring(d$txt, 3, 6) <- d$repl



回答4:


d %>% 
  mutate(txt = str_replace(txt, '0000', repl))

Though probably it will be better with a regex instead of '0000'.



来源:https://stackoverflow.com/questions/58113748/replace-part-of-string-with-mutate-in-a-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!