I have a string in R. I want to find part of the string and append a variable number of zeroes. For example, I have 1 2 3
. Sometimes I want it to be 1 20 3
; sometimes I want it to be 1 2000 3
. If I store the number of appended zeroes in a variable, how can I use it in the "replacement" part of a sub
command?
I have in mind code like this:
s <- '1 2 3'
z <- '3'
sub('(\\s\\d)(\\s.*)', '\\10{z}\\2', s)
This code returns 1 20{z} 3
. But I want 1 2000 3
. How can I get this sort of result?
One way is
s <- '1 2 3'
z <- '3'
zx <- paste(rep(0, z), collapse = '')
sub('(\\s\\d)(\\s.*)', paste0('\\1', zx, '\\2'), s)
but this is a little clunky.