Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R padding 0's inside a string

Tags:

string

regex

r

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:

GT-BU7867-009
GT-BU6523-113
GT-BU6452-001
GT-BU8921-012
like image 431
geodex Avatar asked Nov 22 '12 05:11

geodex


1 Answers

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"
like image 51
thelatemail Avatar answered Nov 09 '22 01:11

thelatemail