I have an arbitrary string, say "1a2 2a1 3a2 10a5" I want to do an arbitrary mathematical operation, say doubling, to some of the numbers, say anything followed by an "a".
I can extract the numbers I want with relative ease
string = "1a2 2a1 3a2 10a5"
numbers = stringr::str_extract_all(string,'[0-9]+(?=a)')[[1]]
and obviously, doubling them is trivial
numbers = 2*(as.integer(numbers))
But I am having problems with placing the new results in their old positions. To get the output "2a2 4a1 6a2 20a5". I feel like there should be a single function that accomplishes this but all I can think of is recording the original indexes of the matches using gregexpr and manually placing the new results in the coordinates.
We can use str_replace_all from stringr to capture numbers followed by "a" and then multiply them by 2 in their callback function.
stringr::str_replace_all(string, "\\d+(?=a)", function(m) as.integer(m) * 2)
#[1] "2a2 4a1 6a2 20a5"
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