2

一月份我问如何替换字符串的前 N ​​个点:replace the first N dots of a string

DWin 的回答很有帮助。可以概括吗?

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)
4

2 回答 2

3

使用sprintf您可以获得所需的输出

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"
于 2013-05-20T20:06:07.337 回答
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
于 2013-05-20T21:07:50.137 回答