Skip to content
Prev 286241 / 398502 Next

I'm sure I'm missing something with formatC() or sprintf()

You said that the values are already character - that's the key.

Compare:
[1] " 2018"
[1] "02018"

Since they are already character, though, here's another option:
x <- c("2108", "60321", "22030") # part of your data
ifelse(nchar(x) == 4, paste("0", x, sep=""), x)
[1] "02108" "60321" "22030"

You could also use:
[1] "02018"

The help for sprintf says this, but not clearly:
    ?0? For numbers, pad to the field width with leading zeros.



Sarah
On Thu, Feb 23, 2012 at 2:16 PM, z2.0 <zack.abrahamson at gmail.com> wrote: