[R] Extracting year from a date object

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Oct 6 13:57:25 CEST 2009


See ?weekdays, which says

Note:

      Other components such as the day of the month or the year are very
      easy to compute: just use 'as.POSIXlt' and extract the relevant
      component.

so

> as.POSIXlt(MyDate)$year+1900
[1] 1994

is how you are expected to do it.

On Tue, 6 Oct 2009, joris meys wrote:

> Hi all,
>
> this one left me a bit puzzled, as I don't seem to find a function to
> perform this easily. I must have overlooked the obvious, so sorry in
> advance.
>
> I have a list of dates in numerical format (i.e. 34576), defined as
> the number of days that passed since january 1st 1900. So I apply the
> function :
>
>> MyDate <-as.Date(34576,origin="1900-01-01")
>> MyDate
> [1] "1994-09-01"
>
> But then I want to do something like :
> MyYear <- a.year.function(MyDate)
>
> MyYear should have the numerical value 1994. Alas, I don't find any
> function like that. I know I can take a substring of MyDate and
> convert to numeric, or even use the function "seq()" :
>
>> length ( seq ( as.Date("1900-01-01"), MyDate, "years" ) ) + 1900 - 1
> [1] 1994
>
> but that seems quite a way around. Can somebody tell me where the
> appropriate function is hiding?
> Thank you in advance.
> Joris
>
> ______________________________________________
> 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.
>

-- 
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