以下是一些解决方案。即使string
是一个字符串的字符向量,它们每个都会工作,在这种情况下,将在其每个组件上进行替换。
1)减少这不使用包。
Reduce(function(x, i) gsub(paste0("\\b", a[i], "\\b"), b[i], x), seq_along(a), string)
## [1] "that was a story about a boy"
2)gsubfngsubfn
就像gsub
但更换参数可以是取代(或某些其他对象)的列表。
library(gsubfn)
gsubfn("\\w+", setNames(as.list(b), a), string)
## [1] "that was a story about a boy"
3)环这不是矢量但是已经添加用于比较。没有包被使用。
out <- string
for(i in seq_along(a)) out <- gsub(paste0("\\b", a[i], "\\b"), b[i], out)
out
## [1] "that was a story about a boy"
注:有周期是否是可能的一些问题。例如,如果
a <- c("a", "A")
b <- rev(a)
做我们想要
- “一” 要与 “A”,然后回到 “A” 再次,或
- “A” 和 “A” 代替被交换。
上面显示的所有解决方案都假定为第一种情况。如果我们想要第二种情况,那么执行两次操作。我们将说明与(2),因为它是最短的,但同样的想法适用于所有这些:
# swap "a" and "A"
a <- c("a", "A")
b <- rev(a)
tmp <- gsubfn("\\w+", setNames(as.list(seq_along(a)), a), string)
gsubfn("\\w+", setNames(as.list(b), seq_along(a)), tmp)
## [1] "this is A story about A test"
不错!我还没有接触过Reduce。非常感谢。 – hjms
已经添加了关于周期的注释 –
还有'regmatches(string,gregexpr(paste(a,collapse =“|”),string))< - list(b)'将与'gsubfn'类似地工作 – thelatemail