1

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.

user697473
  • 2,165
  • 1
  • 20
  • 47

2 Answers2

0

Try concatenate operator from stringi package:

require(stringi)
"abc"%stri+%"123abc"
## [1] "abc123abc"
bartektartanus
  • 15,284
  • 6
  • 74
  • 102
0

Your approach to create the replacement string zx is pretty good. However, you can improve your sub command. If you use lookbehind and lookahead instead of matching groups, you don't need to create a new replacement string. You can use zx directly.

sub("(?<=\\s\\d)(?=\\s)", zx, s, perl = TRUE)
# [1] "1 2000 3"
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168