[Rd] suggestions re trunc.POSIXt

From: Kenn Konstabel <lebatsnok_at_gmail.com>
Date: Wed, 23 Mar 2011 19:21:32 +0000


Dear all,

I hope this is a right place to post this; r-help might be appropriate but it looks like I'm suggesting a change in base package, so I decided to post here. (+ Apologies if that has been changed recently -- the version I'm using is R.2.12.2 on Windows.)

I've noticed an unexpected behavior of trunc.POSIXt:

foo <- seq(as.POSIXct( "2009-10-23 22:00:00"), as.POSIXct("2009-10-26
22:00:00"), by="6 hours")
bar <- trunc(foo, "days")

Now class(bar)[1] returns "POSIXlt" although foo is POSIXct, and then comes the following surprise:

length(foo)    # 13
length(as.POSIXlt(foo))  # still 13
length(bar)   # 1
length(as.POSIXct(bar))  # again 13

It would be nice if trunc would preserve the class as POSIXct, for example, using
 trunc.POSIXct <- function(x, ...) as.POSIXct(trunc.POSIXt(x,...))

On the other hand, I noticed that

> sapply(bar, length)

# sec min hour mday mon year wday yday isdst # 1 1 1 13 13 13 13 13 1

So trunc makes the first three elements shorter which also breaks `[.POSIXlt` . This is also the reason why length(bar) returns 1 as it just uses the length of first element. So I'd suggest changig this too, replacing the lines like x$sec <- 0 by x$sex[] <- 0 (the second version would preserve the number of elements). (Changed version at the end). It doesn't seem like this change could possibly break any existing code.

Best regards,
Kenn

Kenn Konstabel
Department of Chronic Diseases
National Institute for Health Development Hiiu 42
Tallinn, Estonia

######

trunc.POSIXt <- function (x, units = c("secs", "mins", "hours", "days"), ...) {
# changed x$sec <- 0 to x$sec[]<-0 to preserve the number of elements

    units <- match.arg(units)
    x <- as.POSIXlt(x)
    if (length(x$sec))

        switch(units, secs = {
            x$sec <- trunc(x$sec)
        }, mins = {
            x$sec[] <- 0
        }, hours = {
            x$sec[] <- 0
            x$min[] <- 0L
        }, days = {
            x$sec[] <- 0
            x$min[] <- 0L
            x$hour[] <- 0L
            x$isdst <- -1L
        })

    x
}

R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Wed 23 Mar 2011 - 19:24:00 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 24 Mar 2011 - 00:40:37 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive