6

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)
2
  • Did you check stackoverflow.com/questions/5812493 Commented Jul 28, 2017 at 8:21
  • sprintf("%010s", foo) Commented Jul 28, 2017 at 8:39

1 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Accepted as answer because it works. Ideally, should be possible to do this in base R with ease.
@user3614648 You could also use gsub(" ", "0", formatC(foo, width = 10)) base R functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.