[Rd] Operations on difftime (abs, /, c)

From: Stavros Macrakis <macrakis_at_alum.mit.edu>
Date: Sun, 22 Feb 2009 16:51:49 -0500

Forwarded from the r-help group -- r-devel seems more appropriate per Duncan's recent email.


Since both comparison and negation are well-defined for time differences, I wonder why abs and division are not defined for class difftime. This behavior is clearly documented on the man page: "limited arithmetic is available on 'difftime' objects"; but why? Both are natural, semantically sound, and useful operations and I see no obvious reason that they should give an error:

     sec <- as.difftime(-3:3,units="secs")
     hour <- as.difftime(-3:3,units="hours")

     abs( sec ) => error  ... why not 3 2 1 0 1 2 3 secs?
     hour/sec => error   ... why not 3600, 3600, ... (dimensionless numbers)?

Of course, it is trivial to overload these operations for difftime-class arguments:

     abs.difftime <- function(x) ifelse(x<0,-x,x)

> abs(sec)

   [1] 3 2 1 0 1 2 3

   `/.difftime` <-

      function (e1, e2)
       if (!inherits(e2, "difftime"))
     structure(unclass(e1)/e2, units = attr(e1, "units"), class = "difftime")
       else if (inherits(e1, "difftime"))
     as.numeric(e1,attr(e2, units = "units"))/as.numeric(e2)
     stop("second argument of / cannot be a \"difftime\" object")    #
1/hour remains incorrect

   > hour/sec
   [1] 3600 3600 3600 NaN 3600 3600 3600

Along the same lines, I don't understand why concatenation (c) should strip the class of difftime, but not of POSIXt/ct:

    class( c(sec) ) => integer <<< class and units attribute are stripped

    class( c(sec,hour) ) => integer <<< doesn't convert to common unit, giving meaningless result

    class( c(Sys.time()) ) => "POSIXt" "POSIXct"

Again, c.difftime would be easy enough to define if it's the right thing to do.

So why wouldn't it be the right thing to do? Is there some semantic or stylistic issue I'm missing here?


R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Sun 22 Feb 2009 - 20:53:59 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 Sun 22 Feb 2009 - 22:30:32 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