I would like to add leading zeros to an alphanumeric string for a total of ten characters. It is possible, however, that there is a space in between the characters.
TestID <- c("1b4 7A1")
gsub(" ","0",sprintf("%010s", TestID))
This code adds leading zeros, but also replaces the empty space within the string with a zero. Is there a way to add the zeros only in front of the string?
# [1] "0001b4 7A1"
You could use str_pad
from package stringr
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"
We can use sub
sub('^', paste(rep(0,3), collapse=''), TestID)
#[1] "0001b4 7A1"
If it is to add 0 at the front
paste0('000', TestID)
A base R solution for strings of variable lengths could be
paste0(paste(rep("0", 10 - nchar(TestID)), collapse=''), TestID)
# [1] "0001b4 7A1"
Can also use the stringi
package.
library(stringi)
stri_pad_left(TestID, pad="0", width=10)
# [1] "0001b4 7A1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With