Add lead 0 with gsub

I would like to add leading zeros to the alphanumeric string for just ten characters. It is possible, however, that there is a space between the characters.

TestID <- c("1b4 7A1") gsub(" ","0",sprintf("%010s", TestID)) 

This code adds leading zeros, but also replaces the empty space inside the string with zero. Is there a way to add zeros just before the string?

 # [1] "0001b4 7A1" 
+6
source share
4 answers

You can use str_pad from the stringr package and do:

 str_pad(TestID, width=10, side="left", pad="0") 

This gives:

 > str_pad(TestID, width=10, side="left", pad="0") [1] "0001b4 7A1" 
+5
source

We can use sub

 sub('^', paste(rep(0,3), collapse=''), TestID) #[1] "0001b4 7A1" 

If you need to add 0 to the front

 paste0('000', TestID) 
+2
source

The basic solution R for variable-length strings can be

 paste0(paste(rep("0", 10 - nchar(TestID)), collapse=''), TestID) # [1] "0001b4 7A1" 
+2
source

You can also use the stringi package.

 library(stringi) stri_pad_left(TestID, pad="0", width=10) # [1] "0001b4 7A1" 
+1
source

All Articles