Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add leading 0 at a specific position in a string (R)

I have a list of strings of this kind:

f<-c("CC 982","RX 112","TR 002","FF 1328")

I need to add a leading 0, as with the str_pad function, at the beginning of the numerical portion, to get to this:

"CC 0982" "RX 0112" "TR 0002" "FF 1328"

For now, I have tried with sub

sub('(.{2})(.{1})(.{3})', "\\1\\20\\3", f) 

Close enough, but I don't want the leading 0 if the numerical string has 4 digits. What is the solution here? Thank you

like image 939
AVal Avatar asked Dec 18 '22 05:12

AVal


2 Answers

Using sub you could modify to

sub("(\\D*)(\\b\\d{1,3}\\b)", "\\10\\2", f)
# [1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"

This will only catch numbers up until 3 digits and modify them

like image 122
David Arenburg Avatar answered Dec 30 '22 21:12

David Arenburg


We can split the string by space and then use sprintf to join the components

d1 <- do.call(rbind, strsplit(f, "\\s+"))
sprintf("%s %04d", d1[,1], as.numeric(d1[,2]))
#[1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"

Or with gsubfn/sprintf we get the expected output

library(gsubfn)
gsubfn("(\\d+)", ~sprintf("%04d", as.numeric(x)), f)
#[1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"
like image 27
akrun Avatar answered Dec 30 '22 21:12

akrun