替换重新访问的字符串的前N个点

时间:2021-09-22 09:31:25

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

在1月份,我问了如何替换一个字符串的第一个N个点:替换字符串的第一个N个点。

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)

2 个解决方案

#1


3  

Using sprintf you can have the desired output

使用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"

#2


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

#1


3  

Using sprintf you can have the desired output

使用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"

#2


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