Prevent Regex from Overwriting Previous Statement

78 views Asked by At

I have the following string:

a = "in the year 2010-01-01 there was a red dog and in the year 2011-01-01 there was a blue cat"

My Problem: In the above string, I want to replace every 2010 with 2011 and every 2011 with 2012.

I tried the following code:

b = gsub("2010", "2011", a)
b = gsub("2011", "2012", b)

But it overwrites my progress!

I did this with 3 mini statements:

b = gsub("2010", "temp", a)
b = gsub("2011", "2012", b)
b = gsub("temp", "2011", b)

But is there a quicker way to do this in a single line of code?

2

There are 2 answers

1
Tim Biegeleisen On BEST ANSWER

If I understand correctly, you can simply replace 2011 to 2012 first, followed by 2010 to 2011, in that order:

b <- gsub("2011", "2012", b, fixed=TRUE)
b <- gsub("2010", "2011", b, fixed=TRUE)

More generally, you could use a regex replacement with a callback function.

0
Mark On
stringr::str_replace_all(a, c("2011" = "2012", "2010" = "2011"))

Or with base R:

a |> gsub("2011", "2012", x = _) |> gsub("2010", "2011", x = _)