0

The answers to similar questions on adding leading zeros do not work for me. I have a data.frame with just 1 column but many thousands or rows. The entries are of data type num. Some of the numeric values are 10 digits in length (which is correct) but some are 9 digits in length and others 8 digits in length. I want all entries to be 10 digits in length, and so shorter numbers need to be preceded by leading zeros. The entries that are already 10 digits are to be ignored. I am just beginner in R so am having difficulty. Any help will be appreciated. I have tried

paste (rep)

sprintf

but am just getting into a mess. Ideally, I want to keep the data.frame as num but if I have to change to type char that would probably be oaky. Thanks.

I tried previous answers but got this error

Error in sprintf("%010d", CHI3$DoB.Chi) : invalid format '%010d'; use format %f, %e, %g or %a for numeric objects

Stewart Wiseman
  • 675
  • 2
  • 7
  • 14
  • 2
    Voting to close as duplicate. Use `sprintf` as described here: http://stackoverflow.com/a/5812607/602276 – Andrie Jun 30 '13 at 14:59
  • If you want the column to be numeric, why do you care about leading zeros? Do you just want to print to the R console with leading zeros? – Roland Jun 30 '13 at 15:01
  • The leading zero means something. The 10 digit is a code, eg, 0707921234 where the first four digits refer to 7 July but when I imported from Excel the leading zeros got dropped. I need them back. – Stewart Wiseman Jun 30 '13 at 15:17
  • On the information you recently added: assuming that Chi is a numeric (not an integer), use `%010f` or `%010.0f` (to suppress the decimal) instead of `%010d`. ([reference](http://rss.acs.unt.edu/Rdoc/library/base/html/sprintf.html)). – drf Jun 30 '13 at 15:49
  • Thank you drf. Perfect. I had tried that but did not appreciate how to suppress the decimal. – Stewart Wiseman Jun 30 '13 at 16:18

0 Answers0