Given sample string:
tst_str <- c("abc", "123", "klm", "lop")
I would like to make the following replacements:
abc -> za12
123 -> poi
klm -> uyt
Desired results
Simple nesting of gsub
calls delivers the result:
gsub(
pattern = "abc",
replacement = "za12",
x = gsub(
pattern = "123",
replacement = "poi",
x = gsub(
pattern = "klm",
replacement = "uyt",
x = tst_str
)
)
)
# [1] "za12" "poi" "uyt" "lop"
Problem
I would like to arrive at identical results using purrr::map*
or purrr::reduce
functions. My initial take was to make use of purrr::reduce2
purrr::reduce2(
.x = c("abc", "123", "klm"),
.y = c("za12", "poi", "uyt"),
.f = function(x, y, init) {
gsub(pattern = x,
replacement = y,
x = init)
},
.init = tst_str
)
Clearly this is not the right way of doing that:
Warning message: In gsub(pattern = x, replacement = y, x = init) :
argument 'pattern' has length > 1 and only the first element will be used
Notes
The solution has to be based on
purrr::
or other Higher Order Functiondo.call
can do as well
The problem is not practical;
multigsub
and similar functions solve such tasks easily.