Skip to content
Prev 13391 / 63424 Next

proposed change to [.POSIXct

Copying all attributes may very well be troublesome.  Perhaps the approach
taken in [.difftime or in [.times would be more appropriate:
function (x, ..., drop = TRUE) 
{
    cl <- oldClass(x)
    class(x) <- NULL
    val <- NextMethod("[")
    class(val) <- cl
    attr(val, "units") <- attr(x, "units")
    val
}
<environment: namespace:base>
function (x, ..., drop = TRUE) 
{
    cl <- class(x)
    class(x) <- NULL
    val <- NextMethod("[")
    attr(val, "format") <- attr(x, "format")
    attr(val, "origin") <- attr(x, "origin")
    class(val) <- cl
    val
}


Likewise, the new [.POSIXct would be:

"[.POSIXct" <-
function (x, ..., drop = TRUE) 
{
    old.tzone <- attr(x,"tzone")
    old.class <- class(x)
    class(x) <- NULL
    val <- NextMethod("[")
    class(val) <- old.class
    attr(val,"tzone") <- old.tzone
    val
}

The functions [.difftime and [.times preserve attributes when it's sensible
to do so.  I think POSIXct objects should follow the same rule.
I think it should be preserved because in doing a subset operation does not
change the elements of an object, it just selects certain elements.  I'm not
sure what you mean about the history being broken.
My problems arose from trying to use the seq function with POSIXct objects.

Here is a toy example:

start <- ISOdate(1952,03,01,hour=0)
end <- ISOdate(2004,03,01,hour=0)

xx <- seq(start,end,by="months")
yy <- seq(start[1],end[1],by="months")

all(as.numeric(xx)==as.numeric(yy))
as.numeric(xx)==as.numeric(yy)

In my opinion, these two sequences should be the same. Since subsetting the
vectors causes their printed values to be different, the whole sequence is
thrown off even though the underlying values for start and end are the same:
[1] -562896000
attr(,"tzone")
[1] "GMT"
[1] -562896000
[1] 1078099200
attr(,"tzone")
[1] "GMT"
[1] 1078099200
I hope this case is sufficient for you to consider this proposed change.
The r-list contains frequent posts by people who don't understand the
underlying implementation of dates in R.  I think this change will reduce
the cases in which unsuspecting users have their tzone attribute stripped
because of a subset operation.

Thanks again for your time in addressing this issue Professor Ripley.

Cheers,
Whit