[R] 2 questions : format and hh:mm

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Jul 29 12:22:30 CEST 2004


On Thu, 29 Jul 2004, Bruno Cutayar wrote:

> 
> 
> Dear R-users,
> i have two questions :
> 
> 1- first of all, i wish to know the way to obtain a serie with a format 
> like "00" : ( "01","02","03","04"....) or like postal code 
> ("01100","02222").
> for instance, i do :
>  > format(strptime(as.character(c(1:4)),"%H"),"%H")
> but it sounds complicate and not really efficient....!

It is not clear what you want to do here.  If you want to format numbers 
including leading zeros, see ?sprintf or ?formatC. e.g. 
> formatC(1:4, width=2, flag="0")
[1] "01" "02" "03" "04"

>  2- i search to generate a serie of hours and minutes on 24h :
> "00:00" , "00:01", "00:02", "00:03", ...,...,  "23:59"
> for instance, i do :
>  > x <- format( strptime (as.character(rep(0:23,each=60)),"%H"),"%H")
>  > y <- format( strptime (as.character(rep(0:59,24)),"%M"),"%M")
>  > paste (x,y,sep=":")
> it works but is it an another way to obtain this ?

See ?seq.POSIXt.  E.g.

base <- trunc(Sys.time(), "days") # midnight last night
x <- seq(base, base+86400-59, by="mins")
format(x, "%H:%M")

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list