2

In January I asked how to replace the first N dots of a string: replace the first N dots of a string

DWin's answer was very helpful. Can it be generalized?

df.1 <- read.table(text = '

         my.string     other.stuff

     1111111111111111     120
     ..............11     220
     11..............     320
     1...............     320
     .......1........     420
     ................     820
     11111111111111.1     120

', header = TRUE)

nn <- 14

# this works:

df.1$my.string <- sub("^\\.{14}", paste(as.character(rep(0, nn)), collapse = ""), 
df.1$my.string)

# this does not work:

df.1$my.string <- sub("^\\.{nn}", paste(as.character(rep(0, nn)), collapse = ""), 
df.1$my.string)
Community
  • 1
  • 1
Mark Miller
  • 12,483
  • 23
  • 78
  • 132
  • Surely, but you have to replace with a function of some sort, so that you can replace with a proper string length when each match is made. For example in Perl: `s/^\.{1,14}(?=\d)/'0' x length $&/meg` – Qtax May 20 '13 at 20:03
  • Why the downvote? This is a well written question that includes reproducible code -- in those respects better than 3/4 or more of the questions we see hereabouts... – Josh O'Brien May 20 '13 at 20:13
  • It's hard to fathom how someone with ~1.5k rep could expect a variable name within a string to resolve. But I removed my downvote. – Matthew Plourde May 20 '13 at 20:18
  • I admit I need to study regular expressions much more and perhaps I could have obtained an answer with RegexBuddy if I had devoted more time to it before posting. – Mark Miller May 20 '13 at 20:22

2 Answers2

3

Using sprintf you can have the desired output

nn <- 3
sub(sprintf("^\\.{%s}", nn),
    paste(rep(0, nn), collapse = ""), df.1$my.string)

## [1] "1111111111111111" "000...........11" "11.............."
## [4] "1..............." "000....1........" "000............."
## [7] "11111111111111.1"
dickoa
  • 18,217
  • 3
  • 36
  • 50
0
 pattstr <- paste0("\\.", paste0( rep(".",nn), collapse="")  )
 pattstr
#[1] "\\..............."
 df.1$my.string <- sub(pattstr, 
                       paste0( rep("0", nn), collapse=""),
                       df.1$my.string)

> df.1
         my.string other.stuff
1 1111111111111111         120
2  000000000000001         220
3 11..............         320
4  100000000000000         320
5  00000000000000.         420
6  00000000000000.         820
7 11111111111111.1         120
IRTFM
  • 258,963
  • 21
  • 364
  • 487