[R] Vectors of years, months, and days to dates?

Shin, Daehyok sdhyok at email.unc.edu
Tue Jun 8 06:52:26 CEST 2004


Thanks, Richard.
This is what I was looking for.
As you said, the chron package seems so useful that I will use it a lot.
I don't think the performance gain (53:31) is not what we can neglect.
Still, I am wondering why this kind of intuitive interface is not supported
through the base package.

Daehyok Shin (Peter)

> -----Original Message-----
> From: Richard A. O'Keefe [mailto:ok at cs.otago.ac.nz]
> Sent: Monday, June 07, 2004 PM 10:50
> To: sdhyok at email.unc.edu
> Subject: RE: [R] Vectors of years, months, and days to dates?
>
>
> 	as.Date(c(years, months, days))
>
> That would put all the years, followed by all the months,
> followed by all the days, in one vector.
>
> Try the chron package, where you can use
>     julian(y=years, x=months, d=days)
> 	# vectors => vector of day numbers (I really mean 'x', not 'm')
>     chron(julian(...))
> 	# vector of day numbers => vector of chron objects
>     as.POSIXlt(chron(...))
> 	# vector of chron objects => vector of POSIXlt objects
>
> So:
>     ymd.to.POSIXlt <-
>         function (y, m, d) as.POSIXlt(chron(julian(y=y, x=m, d=d)))
>
> Now,
> > n <- 100000
> > y <- sample(1970:2004, n, replace=TRUE)
> > m <- sample(1:12,      n, replace=TRUE)
> > d <- sample(1:28,      n, replace=TRUE)
> > system.time(ymd.to.POSIXlt(y, m, d))
> [1]  8.78  0.10 31.76  0.00  0.00    # user cpu, system cpu, elapsed
> > system.time(as.POSIXlt(paste(y,m,d, sep="-")))
> [1] 14.64  0.13 53.30  0.00  0.00
>
> This was on a 500MHz SunBlade100, a slow machine by today's standards.
> There *is* a time advantage for the approach you prefer, but it's less
> than a factor of 2.
>
> 	Is there no one supporting my idea?
>
> It _is_ supported, via the chron() package.  Just add ymd.to.POSIXlt
> to your .Rprofile
>
> It may even be that chron objects do everything you need.
>




More information about the R-help mailing list