Stavros Macrakis
2009-Feb-17 02:17 UTC
[R] Problem with +(POSIXt, difftime) dispatching -- WAS: How to create sequence of constant time interval
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` <- `+` plus(t0,halfhour.mins) "2009-01-01 00:30:00 EST" plus(t0,halfhour.mins*c(0,1)) "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 `+`. -s 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?
Possibly Parallel Threads
- (Date + difftime) and (POSIXt + difftime) does not use date/time arithmetics (PR#14067)
- Adding difftime objects to POSIXt objects
- Incompatible methods ("-.POSIXt", "Ops.difftime") for "-"
- Wishlist: In documentation, say that `+.Date`(Date, difftime) should be called directly or remove 'or an object of class "difftime"' (PR#14072)
- How to convert Datetime numbers from Excel to POSIXt objects