[R] Accessing date subfields

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Jun 20 14:48:53 CEST 2006


Maciej Radziejewski <maciejr_copies at yahoo.com> writes:

> Hello,
> 
> I can't figure out a "proper" way to extract the month number from a Date class variable. I can do it like this:
> 
> > today <- as.Date(Sys.time())
> > as.integer (format.Date (today, "%m"))
> 
> but it must be inefficient, since I convert a date to text and back to a number. I tried:
> 
>  > months(today)
> 
> but the months() function returns the name of the month, not the month number. I need to process some time series of station data using  season-dependent criteria, so I need the months numerically.
> 
> Thanks in advance for any help,

Wrong class, Date (and POSIXct) objects are basically numeric (time in
days, resp. seconds, since Jan. 1, 1970):

> structure(1,class="Date")
[1] "1970-01-02"
> structure(1,class="POSIXct")
[1] "1970-01-01 01:00:01 CET"

Instead, try:


> as.POSIXlt(Sys.time())$mon
[1] 5

(NB: zero-based...)

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list