5

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)
socialscientist
  • 3,759
  • 5
  • 23
  • 58

1 Answers1

3

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"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • While in the above example all of the string is numeric, what if we have e.g. "546G" as one of the elements? I am hoping to have something that doesn't coerce this to numeric. The example is updated to provide a more relevant case. – socialscientist Jul 28 '17 at 08:05
  • Accepted as answer because it works. Ideally, should be possible to do this in base R with ease. – socialscientist Jul 28 '17 at 09:47
  • 1
    @user3614648 You could also use `gsub(" ", "0", formatC(foo, width = 10))` base R functions – akrun Jul 28 '17 at 09:56