[R] Extracting months and years from Dates while keeping order
Dimitri Liakhovitski
dimitri.liakhovitski at gmail.com
Fri May 6 22:38:52 CEST 2011
Perfect - that's it, Gabor, thanks a lot!
Dimitri
On Fri, May 6, 2011 at 4:11 PM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote:
> On Fri, May 6, 2011 at 4:07 PM, Dimitri Liakhovitski
> <dimitri.liakhovitski at gmail.com> wrote:
>> Hello!
>>
>> I'd like to take Dates and extract from them months and years - but so
>> that it sorts correctly. For example:
>>
>> x1<-seq(as.Date("2009-01-01"), length = 14, by = "month")
>> (x1)
>> order(x1) # produces correct order based on full dates
>>
>> # Of course, I could do "format" - but this way I am losing the "Date"
>> quality of the data:
>>
>> x2<-format(x1,"%Y.%m")
>> (x2)
>> order(x2)
>>
>> Not sure it's possible at all: But is there some other way to extract
>> just months and years from Dates (while ingoring days) - but so that
>> it's still somehow a Date object?
>>
>
> Try using the yearmon class in zoo.
>
>> library(zoo)
>> y <- as.yearmon(x1)
>> y
> [1] "Jan 2009" "Feb 2009" "Mar 2009" "Apr 2009" "May 2009" "Jun 2009"
> [7] "Jul 2009" "Aug 2009" "Sep 2009" "Oct 2009" "Nov 2009" "Dec 2009"
> [13] "Jan 2010" "Feb 2010"
>> order(y)
> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14
>
>
> --
> Statistics & Software Consulting
> GKX Group, GKX Associates Inc.
> tel: 1-877-GKX-GROUP
> email: ggrothendieck at gmail.com
>
--
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com
More information about the R-help
mailing list