[R] Problem with +(POSIXt, difftime) dispatching -- WAS: How to create sequence of constant time interval

Stavros Macrakis macrakis at alum.mit.edu
Tue Feb 17 03:17:26 CET 2009

There seems to be a problem in the way `+` is dispatched for
POSIXt/difftime (R 2.8.0 Windows).

With the following definitions:
    t0 <- as.POSIXct('2009-01-01 00:00')
    halfhour.mins <- as.difftime(30,units='mins')

I would have thought that the straightforward answer to Suresh's
question would be something like

    t0 + halfhour.mins * (0:47)

And indeed, if we call the class-specific function (which explicitly
handles the POSIXt + difftime case), we sensibly get:

    `+.POSIXt`(t0, halfhour.mins * (0:47) )
      "2009-01-01 00:30:00 EST" ... "2009-01-01 23:30:00 EST"

But if we use the generic function, it yields an incorrect result
(wrong class, wrong values) as well as a Warning:

    t0 + halfhour.mins * (0:47)
      Time differences in mins
      1230786000 1230786030 ... 1230787410
    Warning message:
    Incompatible methods ("+.POSIXt", "Ops.difftime") for "+"

And even more peculiarly, if the second argument is of length 1, the
result has a different class (though the same warning):

    t0 + halfhour.mins
      "2009-01-01 00:00:30 EST"              <<< POSIXct type correct,
but added seconds
    Warning message:
    Incompatible methods ("+.POSIXt", "Ops.difftime") for "+"

This does not happen with the class-specific function:

    `+.POSIXt`(t0, halfhour.mins)
      "2009-01-01 00:30:00 EST"

I wondered if this sort of problem was inherent to the S3 framework,
but it doesn't seem to be:

    plus <- function(e1,e2) UseMethod("+")
    `+.default` <- `+`

    "2009-01-01 00:30:00 EST"
    "2009-01-01 00:00:00 EST" "2009-01-01 00:30:00 EST"

And the system already defines `+.POSIXt` and `+.Date`. So the problem
seems to be within the primitive `+`.


PS There are other peculiarities in the handling of difftime -- see my
email of Feb 6, 2009 6:17 PM ("Operations on difftime (abs, /, c)") --
which could easily be revised. Is there some reason they shouldn't be?

More information about the R-help mailing list