[R] date conversion

David Winsemius dwinsemius at comcast.net
Thu Mar 17 04:22:02 CET 2011


On Mar 16, 2011, at 10:22 PM, Erin Hodgess wrote:

> Dear R People:
>
> I have a monthly time series which runs from January 1998 to  
> December 2010.
>
> When I use tsp I get the following:
>
>> tsp(ibm$ts)
> [1] 1998.000 2010.917   12.000
>
>
> Is there an easy way to convert this to a seq.Date object, please?
>
> I would like to have something to the effect of
> 1998/01/01 .... 2010/12/01

Several (at least two, anyway) packages have functions to convert  
fractional years:

RSiteSearch("fractional year dates")

or you can use
library(sos)

Most date formats are in days so another option would be something  
along these lines

conv.frac.yr <- function(yr) as.Date( (yr-1970)*(365 + (yr %% 4 ==  
0)), origin="1970-01-01" )

Unfortunately that doesn't take into account leap years in any except  
the current year so:

 > as.Date(sapply(c (1998.000, 2010.917), conv.frac.yr),  
origin="1970-01-01")
[1] "1997-12-25" "2010-11-21"

Not acceptable. Since others have already wrestled with this  use  
their work to your advantage.



>
> Thanks,
> Erin
>
>
>
> -- 
> Erin Hodgess
> Associate Professor
> Department of Computer and Mathematical Sciences
> University of Houston - Downtown
> mailto: erinm.hodgess at gmail.com
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list