[R] Using format to add leading zeroes

jim holtman jholtman at gmail.com
Sat Mar 14 00:20:14 CET 2009

use sprintf:

> sprintf("%04d",15)
[1] "0015"

On Fri, Mar 13, 2009 at 6:17 PM, Jonathan Greenberg
<greenberg at ucdavis.edu> wrote:
> I have a numerical vector which contains a (poorly) formatted time column,
> which, in theory, should be HHMM, but was distributed as an integer, so, for
> 12:15 am, it is saved as "15" (e.g. HHMM = 0015 with the zeroes stripped).
>  I'm trying to use this in conjunction with strptime, but I'm thinking
> because each time is an integer ranging from 1 to 4 digits, I probably need
> to coerce this vector using "format" first to add back the leading zeroes --
> but I can't seem to figure out the specific parameters to send to format().
>  Thoughts?  I could use the pad0 function in PBSmodelling, but it seems to
> only work on one item at a time (not an entire vector) so I thought I'd ask
> here if there's an easy trick to getting where I need to go using on the
> base package and not needing to write a for-next loop to implement pad0.
> Thanks!
> --j
> --
> Jonathan A. Greenberg, PhD
> Postdoctoral Scholar
> Center for Spatial Technologies and Remote Sensing (CSTARS)
> University of California, Davis
> One Shields Avenue
> The Barn, Room 250N
> Davis, CA 95616
> Cell: 415-794-5043
> AIM: jgrn307, MSN: jgrn307 at hotmail.com, Gchat: jgrn307
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?

More information about the R-help mailing list