Reputation: 4232
I am trying to create 10-character strings by padding any number with less than 10-characters with zeroes. I've been able to do this with a number of characters less than 10 but the below is causing a 10-character string to form with spaces at the start. How does one make the leading characters 0s?
# Current code
foo <- c("0","999G","0123456789","123456789", "S")
bar <- sprintf("%10s",foo)
bar
# Desired:
c("0000000000","000000999G","0123456789", "0123456789", "00000000S)
Upvotes: 5
Views: 925
Reputation: 887048
We need
sprintf("%010d", as.numeric(foo))
#[1] "0000000000" "0000000999" "0123456789" "0123456789"
If we have character
elements, then
library(stringr)
str_pad(foo, width = 10, pad = "0")
#[1] "0000000000" "000000999G" "0123456789" "0123456789" "000000000S"
Upvotes: 3