用mutate替换字符串的一部分(在管道中) [英] Replace part of string with mutate (in a pipe)
本文介绍了用mutate替换字符串的一部分(在管道中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想替换字符串的一部分(在前两个下划线之间,第一组始终为 i),如下面的基本R示例所示:
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
如何使用 str_sub<-
或其他字符串函数来做到这一点?
How can I do that either using str_sub<-
or another stringr-function?
推荐答案
这是在管道中使用 str_sub<-
的一种方法。
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
请注意,参数 value
是最后一个,因此必须将其传递给它的名称。
Note that argument value
is the last, so it must be passed assigned to its name.
这篇关于用mutate替换字符串的一部分(在管道中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文