在字符串内填充0。

时间:2022-12-19 19:31:30

I have the following data

我有以下数据

GT-BU7867-09
GT-BU6523-113
GT-BU6452-1
GT-BU8921-12

How do I use R to make the numbers after the hyphen to pad leading zeros so it will have three digits? The resulting format should look like this:

如何用R来表示连字符后的数字,以填充前导0,使它有3位数字?产生的格式应该如下所示:

GT-BU7867-009
GT-BU6523-113
GT-BU6452-001
GT-BU8921-012

3 个解决方案

#1


11  

Base solution:

基本的解决方案:

sapply(strsplit(x,"-"), function(x)
    paste(x[1], x[2], sprintf("%03d",as.numeric(x[3])), sep="-")
)

Result:

结果:

[1] "GT-BU7867-009" "GT-BU6523-113" "GT-BU6452-001" "GT-BU8921-012"

#2


3  

A solution using stringr and str_pad and strsplit

使用stringr和str_pad和strsplit的解决方案。

library(stringr)
    x <- readLines(textConnection('GT-BU7867-09
GT-BU6523-113
GT-BU6452-1
GT-BU8921-12'))

unlist(lapply(strsplit(x,'-'),
       function(x){
         x[3] <- str_pad(x[3], width = 3, side = 'left', pad = '0')
         paste0(x, collapse = '-')}))

[1] "GT-BU7867-009" "GT-BU6523-113" "GT-BU6452-001"
[4] "GT-BU8921-012"

#3


1  

Another version using str_pad and str_extract from package stringr

另一个版本使用str_pad和str_extract从包stringr中提取

library(stringr)   
x <- gsub("[[:digit:]]+$", str_pad(str_extract(x, "[[:digit:]]+$"), 3, pad = "0"), x)

i.e. extract the trailing numbers of x, pad them to 3 with 0s, then substitute these for the original trailing numbers.

也就是提取x的尾数,用0填充到3,然后用这些代替原来的尾数。

#1


11  

Base solution:

基本的解决方案:

sapply(strsplit(x,"-"), function(x)
    paste(x[1], x[2], sprintf("%03d",as.numeric(x[3])), sep="-")
)

Result:

结果:

[1] "GT-BU7867-009" "GT-BU6523-113" "GT-BU6452-001" "GT-BU8921-012"

#2


3  

A solution using stringr and str_pad and strsplit

使用stringr和str_pad和strsplit的解决方案。

library(stringr)
    x <- readLines(textConnection('GT-BU7867-09
GT-BU6523-113
GT-BU6452-1
GT-BU8921-12'))

unlist(lapply(strsplit(x,'-'),
       function(x){
         x[3] <- str_pad(x[3], width = 3, side = 'left', pad = '0')
         paste0(x, collapse = '-')}))

[1] "GT-BU7867-009" "GT-BU6523-113" "GT-BU6452-001"
[4] "GT-BU8921-012"

#3


1  

Another version using str_pad and str_extract from package stringr

另一个版本使用str_pad和str_extract从包stringr中提取

library(stringr)   
x <- gsub("[[:digit:]]+$", str_pad(str_extract(x, "[[:digit:]]+$"), 3, pad = "0"), x)

i.e. extract the trailing numbers of x, pad them to 3 with 0s, then substitute these for the original trailing numbers.

也就是提取x的尾数,用0填充到3,然后用这些代替原来的尾数。