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

(Ted Harding) Ted.Harding at wlandres.net
Thu Feb 23 20:58:25 CET 2012


On 23-Feb-2012 z2.0 wrote:
> I have a four-digit string I want to convert to five digits. Take the
> following frame:
> 
> zip
> 2108
> 60321
> 60321
> 22030
> 91910
> 
> I need row 1 to read '02108'. This forum directed me to formatC previously
> (thanks!) That usually works but, for some reason, it's not in this
> instance. Neither of the syntaxes below change '2108' to '02108.' The values
> in cand_receipts[,1] are of type 'character.'
> 
> cand_receipts[,1] <- formatC(cand_receipts[,1], width = 5, format = 's',
> flag = '0')
> cand_receipts[,1] <- sprintf("%05s", cand_receipts[,1])
> 
>  Any thoughts?
> 
> Thanks,
> Zack

For this (and similar cases):

  formatC(2108,width=5,flag="0")
  # [1] "02108"

For longer strings:

  formatC(2108,width=6,flag="0")
  # [1] "002108"

see ?formatC for more details (the way formatC() aggregates
information about the desired format is somewhat different
from the format syntax in C's printf() and related functions).

Ted.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 23-Feb-2012  Time: 19:58:22
This message was sent by XFMail



More information about the R-help mailing list