I need to replace in string foo bar foo bar bar foo
all foo
to bar
and all bar
to foo
. So the result should look like bar foo bar foo foo bar
.
I have tried this way:
library(stringr)
my_str <- "foo bar foo bar bar foo"
rslt <- str_replace_all(my_str, c("foo", "bar"), c("bar", "foo"))
print(rslt)
but instead I got "bar bar bar bar bar bar" "foo foo foo foo foo foo"
.
Question: How to correct my code so I get bar foo bar foo foo bar
?
Using str_replace_all
multiple replacements and moving the first match to a temporary value.
library(stringr)
str_replace_all(my_str, c("foo" = "tmp", "bar" = "foo", "tmp" = "bar"))
[1] "bar foo bar foo foo bar"
No real reason to do this unless you're unable to install extra packages, but just for fun here's a base R solution (following the "tmp" replacement method in @manotheshark's answer):
Reduce(
function(prev, x) gsub(x[1], x[2], prev),
list(c('foo', 'tmp'), c('bar', 'foo'), c('tmp', 'bar')),
my_str)
# [1] "bar foo bar foo foo bar"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With