Replace part of string with mutate (in a pipe)
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.
d %>%
mutate(txt = str_replace(txt, '0000', repl))
Though probably it will be better with a regex instead of '0000'.
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})