我敢打赌还有另一种方法可以做到这一点,但我的第一个想法是gsubfn:
my_repl <- function(x){
switch(x,a = "[this was an a]",
b = "[this was a b]",
c = "[this was a c]",
z = "[this was a z]")
}
library(gsubfn)
start_string <- sample(letters[1:10], 10)
gsubfn("a|b|c|z",my_repl,x = start_string)
如果您正在搜索列表元素的可接受的有效名称的模式,这也将起作用:
names(my_replacement) <- my_pattern
gsubfn("a|b|c|z",as.list(my_replacement),start_string)
Edit
但坦率地说,如果我真的必须在自己的代码中经常这样做,我可能会这样做for
循环事物,包装在函数中。这是一个简单的版本,使用sub
and gsub
而不是来自的函数stringr:
vsub <- function(pattern,replacement,x,all = TRUE,...){
FUN <- if (all) gsub else sub
for (i in seq_len(min(length(pattern),length(replacement)))){
x <- FUN(pattern = pattern[i],replacement = replacement[i],x,...)
}
x
}
vsub(my_pattern,my_replacement,start_string)
但当然,没有众所周知的内置函数的原因之一可能是像这样的顺序替换不会非常脆弱,因为它们是如此依赖于顺序:
vsub(rev(my_pattern),rev(my_replacement),start_string)
[1] "i" "[this w[this was an a]s [this was an a] c]"
[3] "[this was an a]" "g"
[5] "j" "d"
[7] "f" "[this w[this was an a]s [this was an a] b]"
[9] "h" "e"